当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式

时间:2011-07-29 12:22:34

标签: sql-server-2008 stored-procedures

我在sql server 2008中编写了以下存储过程我收到错误,因为我提到我不知道为什么会这样解决这个

create PROCEDURE dbo.uspTest1
as
    declare @cnt int;
    declare @cnt1 int;
    declare @cnt2 int;

     set @cnt=(SELECT COUNT(EmpID) AS Expr1 FROM tblTest WHERE (FedTaxID = '888888888') AND (TaxTypeCode = 'TX02'))

set @cnt1=(SELECT COUNT(EmpID) AS Expr1 FROM tblTest
WHERE(FedTaxID = '888888888') AND (TaxTypeCode = 'TX03'))
set @cnt2=(SELECT 
    TaxTypeCode, SUM(Amount) 
FROM 
    tblTest 
WHERE
    FedTaxID = '888888888'
    AND TaxTypeCode IN ('TX02', 'TX03')
GROUP BY
    TaxTypeCode)

这是我试过的另一个,这也给我一个错误

create PROCEDURE dbo.uspTest1
as
    declare @cnt int;
    declare @cnt1 int;
    declare @cnt2 int;

     set @cnt=(SELECT     COUNT(EmpID) AS Expr1
FROM         tblTest
WHERE     (FedTaxID = '888888888') AND (TaxTypeCode = 'TX02'))

set @cnt1=(SELECT     COUNT(EmpID) AS Expr1
FROM         tblTest
WHERE     (FedTaxID = '888888888') AND (TaxTypeCode = 'TX03'))

set @cnt2=(SELECT  SUM(Txallt) as txnntot
  FROM (SELECT CASE WHEN  TaxTypeCode = 'tx02' THEN Amount else 0 END as tx02t,
               CASE WHEN  TaxTypeCode = 'tx03' THEN Amount else 0 END as tx03t,
               Amount as txallt
        FROM tbltest
        WHERE FedTaxID = '888888888'
       ))
GROUP BY FedTaxId

This is giving an error as Incorrect Syntax near ')'

所以任何人都能说出我在做什么错误

3 个答案:

答案 0 :(得分:2)

首先,问题是这一行:

set @cnt2=(SELECT TaxTypeCode, SUM(Amount) FROM tblTest 
WHERE FedTaxID = '888888888' AND TaxTypeCode IN ('TX02', 'TX03') 
GROUP BY TaxTypeCode) 

您正在尝试将变量设置为选择2列的查询,您只能将其设置为返回1行且包含1列的值。


在第二个中,您正在创建一个返回表的子查询,因此您需要一个别名。变化

WHERE FedTaxID = '888888888'
         )) 

WHERE FedTaxID = '888888888'
         ) x ) 

答案 1 :(得分:2)

只需取出第一个中的TaxTypeCode

即可
set @cnt2=(SELECT 
    SUM(Amount) 
FROM 
    tblTest 
WHERE
    FedTaxID = '888888888'
    AND TaxTypeCode IN ('TX02', 'TX03')
GROUP BY
    TaxTypeCode)

然而,SUM(Amount).. GROUP BY将返回多行,但您尝试分配给一个变量:结果中的一行将被任意选取@ cnt2

你需要GROUP BY吗?

如果没有,你可以简单地做到这一点:

SELECT
   @cnt = COUNT(CASE TaxTypeCode = 'TX02' THEN EmpID ELSE NULL END),
   @cnt1 = COUNT(CASE TaxTypeCode = 'TX03' THEN EmpID ELSE NULL END),
   @cnt2 = SUM(Amount)
FROM
   tblTest
WHERE
   FedTaxID = '888888888'
   AND
   TaxTypeCode IN ('TX02', 'TX03')

否则,添加样本数据并清楚说明您要做的事情......

答案 2 :(得分:0)

子查询需要别名。这就是错误“语法不正确”的原因)“”。

例如,此查询没有别名,因此运行它会产生相同的“语法错误”错误:

declare @x int
set @x = (select count(*) from (select * from sys.objects))

您可以通过包含子查询的别名来修复上述语句:

declare @x int
set @x = (select count(*) from (select * from sys.objects) AllSysObjects)
select @x