Tsql union in while loop(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联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:while循环中的Tsql联合
基础教程推荐
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
