如何合并返回的行以返回单个表而不是多个窗口?

时间:2019-06-18 10:39:40

标签: sql dynamic while-loop

此代码返回一行,其中包含过去8个季度中每个季度的地址。这些行显示在结果中的单独窗口中,但我想合并结果。

我尝试将'Merge'作为字符串添加到动态SQL的末尾,但这不起作用。

UNION ALL选项是我想要的,但是当我尝试它时,出现以下错误:消息102,级别15,状态1,第9行'ALL'附近的语法不正确。

-下面是我正在使用的代码

ALTER PROCEDURE [dbo].[USP_History_Building] 

        @BUILDING int

AS 

DECLARE @quarterStart int = 2
DECLARE @quarterEnd int = 1
DECLARE @yearStart int = 17
DECLARE @yearEnd int = 19
DECLARE @BUILDING_ID int
DECLARE @year int
DECLARE @quarter int

DECLARE @quarterForDbName nvarchar(4)
DECLARE @sqlStatement nvarchar(max)

SET @year = @yearStart
SET @quarter = @quarterStart
SET @sqlStatement = ''

SET  @BUILDING_ID = @BUILDING


WHILE @year <= @yearEnd
BEGIN
    WHILE ((@year < @yearEnd AND @quarter <= 4) OR (@year = 
           @yearEnd AND @quarter <= @quarterEnd))
    BEGIN
    SET @quarterForDbName = 'Q' + CAST(@quarter AS nvarchar(1)) + 
            CAST(@year AS nvarchar(2))


       SET @sqlStatement = @sqlStatement + 
       'SELECT '''  + @quarterForDbName +  ''' AS Quarter, 
       ADDRESS_POINT_ID, BUILDING_ID, ADDR_LINE_1, ADDR_LINE_2, 
       ADDR_LINE_3, ADDR_LINE_4, ADDR_LINE_5, ADDR_LINE_6, ADDR_LINE_7, 
       ADDR_LINE_8 FROM EDB_'+ @quarterForDbName +'.dbo.POSTAL_ADDRESS PA 
       WHERE PA.BUILDING_ID = ' + CAST(@BUILDING_ID AS VARCHAR)

        SET @quarter = @quarter + 1  

    END
    SET @quarter = 1
    SET @year = @year + 1


END

PRINT @sqlStatement
EXEC (@sqlStatem

预期结果是一个单个结果窗口,其中包含8个季度的地址记录,可以轻松将其复制并粘贴到Excel或其他位置。

0 个答案:

没有答案