简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM