while循环中的Tsql联合

Tsql union in while loop(while循环中的Tsql联合)
本文介绍了while循环中的Tsql联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我试图在更改 where 子句中的某些值时将同一个表与其自身联合在一起.我的问题是循环之间的联合.我不能使用表变量,因为架构太复杂,无法每次都手动编写.临时表似乎是要走的路,但我不知道如何让它工作和正确的语法.

I am trying to union the same table together with itself while changing some value in the where clause. The problem i have is with the union between the loops. I can not use a table variable since the schema is too complicated to write by hand each time. Temp tables seem to be the way to go but I do not know how to get it to work and the correct syntax.

我想要实现的伪代码:

DECLARE @var int, #tempTable
SET @var = someValue

WHILE expressionIncludingVar
  #tempTable = SELECT *
  FROM someTable
  WHERE column = @var
  UNION ALL #tempTable

  SET @var = someChangeToVar

RETRUN #tempTable

查询的结果应该是 #tempTable 因此奇怪的RETURN #tempTable".

The result of the query should be #tempTable hence the weird "RETURN #tempTable".

提前致谢.

另一个硬编码示例:我正在尝试对这样的东西进行硬编码:

Another hardcoded example: I am trying to unhardcode something like this:

 SELECT someAggregateColumns
 FROM table
 WHERE someDateColumn > @date and < someDateColumn < DATEADD(month, 2, @date)
 GROUP BY someColumn
 UNION ALL
 SELECT someAggregateColumns
 FROM table
 WHERE someDateColumn > DATEADD(month, 1, @date) and and < someDateColumn < DATEADD(month, 1, DATEADD(month, 3, @date))
 GROUP BY someColumn
 SELECT someAggregateColumns
 FROM table
 WHERE someDateColumn = DATEADD(month, 2, @date) DATEADD(month, 1, DATEADD(month, 4, @date))
 GROUP BY someColumn
 UNION ALL 
 ....etc

推荐答案

也许递归 CTE 适合您.

Maybe Recursive CTE works for you.

你可以试试这个.

DECLARE @MyTable TABLE(ID INT, ColumnA VARCHAR(10), ColumnB VARCHAR(10))
INSERT INTO @MyTable VALUES
(1,'A', '10'), 
(2,'B', '11'),
(3,'C', '12'),
(4,'D', '13'),
(5,'E', '14'),
(6,'F', '15'),
(7,'H', '16')

DECLARE @var INT = 4

;WITH CTE AS (
    SELECT * FROM @MyTable WHERE ID = @var
    UNION ALL 
    SELECT T.* FROM CTE INNER JOIN @MyTable T ON CTE.ID - 1 = T.ID 
)
SELECT * INTO #tempTable FROM CTE

SELECT * FROM #tempTable

DROP TABLE #tempTable

这篇关于while循环中的Tsql联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)