合并SQL查询的结果

时间:2016-07-07 14:31:15

标签: sql-server tsql union

我正在尝试将此查询的结果合并到一个列表中的所有数据。 '联盟'没有帮助......

任何想法?

DECLARE @cnt INT = 0
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @items AS VARCHAR(500)
DECLARE @stline AS VARCHAR(500)



while @cnt < 101

begin 

set @items = 'LG_0' + convert(nvarchar(3),@cnt) + '_ITEMS'
set @stline = 'LG_0' + convert(nvarchar(3),@cnt) + '_01_STLINE'

if (OBJECT_ID (@items) is not null and OBJECT_ID(@stline) is not null ) 

set @SQLQuery = 'SELECT
    ITM1.CODE, itm1.NAME, max (stl.date_) [latest date] , price as [latest price], '+ convert(nvarchar(3),@cnt) + ' as [proje kodu]

FROM ' + @items + ' ITM1 INNER JOIN ' + @stline +  ' STL 
    ON ITM1.LOGICALREF = STL.STOCKREF
WHERE PRICE > 0 
    AND TRCODE = 1 
    AND CANCELLED = 0 
    AND INVOICEREF > 0 


    group by code, name, stl.DATE_ , price

    '

    exec (@SQLQuery)



    set @cnt = @cnt +1 


end 

结果如下:

Result

但是我想要他们所有联合编辑...(对不起代码问题,我必须在这里添加更多打字)

2 个答案:

答案 0 :(得分:1)

我不知道为什么UNION不适合你,但以下情况应该有效:

 DECLARE @cnt INT = 0
    DECLARE @SQLQuery AS NVARCHAR(MAX)  = ''
    DECLARE @items AS VARCHAR(500)
    DECLARE @stline AS VARCHAR(500)

    while @cnt < 101

    begin 

    set @items = 'LG_0' + convert(nvarchar(3),@cnt) + '_ITEMS'
    set @stline = 'LG_0' + convert(nvarchar(3),@cnt) + '_01_STLINE'

    if (OBJECT_ID (@items) is not null and OBJECT_ID(@stline) is not null ) 

    set @SQLQuery = @SQLQuery + 'SELECT
        ITM1.CODE, itm1.NAME, max (stl.date_) [latest date] , price as [latest price], '+ convert(nvarchar(3),@cnt) + ' as [proje kodu]

        FROM ' + @items + ' ITM1 INNER JOIN ' + @stline +  ' STL 
            ON ITM1.LOGICALREF = STL.STOCKREF
        WHERE PRICE > 0 
            AND TRCODE = 1 
            AND CANCELLED = 0 
            AND INVOICEREF > 0 
        GROUP BY code, name, stl.DATE_ , price

        UNION ALL
        '    
        set @cnt = @cnt +1 

    end 

    -- SUBSTRING to remove last UNION ALL
    SELECT @SQLQuery = SUBSTRING(@SQLQuery, 1, LEN(@SQLQuery) - 18) 

    -- For debugging purposes
    -- PRINT @SQLQuery
    exec (@SQLQuery)

我无法对其进行测试,但您可以对exec发表评论,并取消注释PRINT以查看正在生成的查询。它使调试动态SQL变得更加容易。

此代码背后的理念:首先根据您的条件构建UNION ALL查询。最后删除最后一个UNION ALL,然后执行代码。

答案 1 :(得分:0)

display:table-cell