2010-08-12 134 views
1

我想一個SELECT查詢返回的特定值,如果一個嵌套子查詢的次數爲0 ...SQL子查詢COUNT CASE

SELECT 
    (SELECT (CASE COUNT(*) = 0 THEN 'TRUE' ELSE 'FALSE' END) 
    FROM List 
    WHERE Status = 1 
     AND Deleted = 1 
) AS Status 

這不起作用,什麼是錯的這個語法?

回答

8

我相信你想有一個case語句看起來像這樣:

CASE 
WHEN EXISTS(SELECT * FROM list WHERE Status = 1 AND Deleted = 1) THEN 'FALSE' 
ELSE 'TRUE' 
END 
1

您的查詢缺少在CASE語句的WHEN關鍵字。

SELECT 
    (SELECT (CASE WHEN COUNT(*) = 0 THEN 'TRUE' ELSE 'FALSE' END) 
    FROM List 
    WHERE Status = 1 
     AND Deleted = 1 
) AS Status 

您可以用走,或者您可以通過刪除外部SELECT語句簡化查詢。而且,括號也是可選的。

SELECT CASE WHEN COUNT(*) = 0 THEN 'TRUE' ELSE 'FALSE' END 
FROM List 
WHERE Status = 1 
    AND Deleted = 1