case subquery in sql server 2008

吃可爱长大的小学妹 提交于 2020-01-15 14:14:08

问题


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)

Error: Subqueries are not allowed in this context. Only scalar expressions are allowed.


回答1:


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. 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.

To fix it, just replace select count(*) with 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. Store the result in a variable and PRINT the variable:

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;


来源:https://stackoverflow.com/questions/5190698/case-subquery-in-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!