[英]case subquery in sql server 2008
the followings statements gives an error 以下陈述给出了错误
print (case when exists (select count(*) from tblCustomerProductsDiscount PD where PD.cust_ID=138 and PD.pack_detl_ID = 1) then 0 end) print(存在时的情况(从tblCustomerProductsDiscount PD中选择count(*),其中PD.cust_ID = 138,PD.pack_detl_ID = 1)然后0结束)
Error: Subqueries are not allowed in this context. 错误:在此上下文中不允许子查询。 Only scalar expressions are allowed. 只允许标量表达式。
First of all, while your intention is quite clear, the script in its current form doesn't make sense, and here's why. 首先,虽然你的意图非常明确,但目前形式的剧本没有意义,这就是原因。
You are checking for the existence of rows in the select count(*)...
subselect, but the fact is, COUNT()
always returns a value. 您正在检查select count(*)...
subselect中是否存在行,但事实是, COUNT()
始终返回一个值。 In case of no rows for the specified condition it will return 0
, but that would still be a row returned by the subquery, and EXISTS
would evaluate to TRUE
in any case. 如果指定条件没有行,它将返回0
,但仍然是子查询返回的行,并且EXISTS
在任何情况下都将计算为TRUE
。
To fix it, just replace select count(*)
with select *
. 为了解决这个问题,只需更换select count(*)
与select *
。
Another thing is the error. 另一件事是错误。 Subqueries are not allowed in this context , and that is final . 在此上下文中不允许使用子查询 ,这是最终的 。 With PRINT
you cannot use a subquery in any form. 使用PRINT
您不能以任何形式使用子查询。 Store the result in a variable and PRINT
the variable: 将结果存储在变量中并将变量PRINT
:
declare @result int;
set @result = case
when exists (
select *
from tblCustomerProductsDiscount PD
where PD.cust_ID=138 and PD.pack_detl_ID = 1
)
then 0
end
print @result;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.