Iterative Union ALL

时间:2016-03-31 02:09:55

标签: sql sql-server iteration union

我有一个大的SQL Server 2012数据库,我正在查询3个表来创建5个字段的结果集。

我想在WHILE - 循环中重复此查询,并在每个循环中获得的结果集“UNION ALL”。这个迭代将在一个变量上:@this_date,它将在过去6年内增加并在今天的日期停止。

在每次迭代时,SELECT将获得不同的结果集。

所以我试图按如下方式对存储过程进行编码:

Declare @the_date as Date, 
        @to_date as Date 

-- I setup the above dates, @the_date being 6 years behind @to_date
--  Want to loop for each day over the 6-year period


WHILE (@the_date <= @to_date) 
BEGIN 

--  the basic select query looks like this

Select Table1.Field-1, Table2.Field-2 ...
FROM Table1
Inner Join  Table2 ...
On ( ..etc..  )

--  the JOIN conditions are based on table.attributes which are compared with 
-- @the_date to get a different result set each time

-- now move the date up by 1

DateAdd(Day, +1, @the_date)

-- want to concatenate the result sets

UNION ALL 
END 

上面给出了语法错误:

  

关键字“Union”附近的语法不正确。

欢迎任何解决我问题的想法 - 谢谢。

1 个答案:

答案 0 :(得分:1)

不要使用UNION。无论如何你不能在循环中。而是将每次迭代的结果存储在临时表或表变量中,并从临时表/表变量中进行选择。

DECLARE @the_date as Date, 
        @to_date as Date

CREATE TABLE #t (Col1 VARCHAR(100))

WHILE (@the_date <= @to_date) 
BEGIN
   INSERT #t (Col1) SELECT ... etc
   DateAdd(Day, +1, @the_date)
END

SELECT Col1 FROM #t

也就是说,如果您提供一些示例数据和预期结果,我们可能会帮助您提供更高效的基于集合的解决方案。您应尽可能避免在RDBMS中进行迭代循环。