SQL Server - 使用UNION进行变量赋值

时间:2014-06-04 14:24:11

标签: sql sql-server

我尝试使用UNION ALL分配变量值,但收到错误:

  

在包含top的语句中不允许进行变量赋值   级别UNION,INTERSECT或EXCEPT运算符。

如何使用UNION分配值?这是我试图制作的sql:

SELECT @Totals = SUM(Quantity)      
  FROM ConsData A WITH(NOLOCK)      
INNER JOIN #TmpData B ON B.DataId = A.DataId 
INNER JOIN Data cp ON cp.DataId = A.DataId           
 WHERE A.Status = -1 AND cp.Date IS NOT NULL
UNION ALL
SELECT @Totals = cg.Total  
        FROM ConsDataGenerated cg
            INNER JOIN #TmpData B ON B.DataId = cg.DataId
            INNER JOIN Data cp ON cp.DataId = B.DataId
        WHERE cp.Date IS NULL   

1 个答案:

答案 0 :(得分:1)

尝试这样的事情......

DECLARE @Totals1 INT, @Totals2 INT, @GrandTotal INT;

SELECT @Totals1 = SUM(Quantity)      
FROM ConsData A WITH(NOLOCK)      
INNER JOIN #TmpData B ON B.DataId = A.DataId 
INNER JOIN Data cp ON cp.DataId = A.DataId           
WHERE A.Status = -1 AND cp.Date IS NOT NULL


SELECT @Totals2 = cg.Total    --<-- Assuming this returns a Scalar value
FROM ConsDataGenerated cg
INNER JOIN #TmpData B ON B.DataId = cg.DataId
INNER JOIN Data cp ON cp.DataId = B.DataId
WHERE cp.Date IS NULL  

SELECT @GrandTotal = ISNULL(@Totals1, 0) + ISNULL(@Totals2, 0);