2012-07-20 68 views
1

我需要創建一個查詢,看起來像這樣:CASE語句內部存在

SELECT attr
FROM SomeTable B
WHERE EXISTS
    (CASE WHEN B.some_attr = 0
        THEN (SELECT x FROM C WHERE B.z = z)
     WHEN B.some_attr = 1
        THEN (SELECT x FROM D WHERE B.z = x)
     END)

但是SQL Server將拒絕執行此帶來一些語法錯誤。
如何修改此查詢以使其工作?

編輯:我加入了錯誤:

Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'CASE'.
Msg 156, Level 15, State 1, Line 6 Incorrect syntax near the keyword 'WHEN'.
Msg 102, Level 15, State 1, Line 8 Incorrect syntax near ')'.

+4

「有些語法錯誤」將是一個很大的幫助大家誰願意幫助你。 – DaveRlz 2012-07-20 14:00:45

回答

2

試試這個:

SELECT A 
FROM B 
WHERE 
    CASE 
    WHEN B.some_attr = 0 AND EXISTS(SELECT x FROM C WHERE B.z = z) THEN 1 
    WHEN B.some_attr = 1 AND EXISTS(SELECT x FROM D WHERE B.z = x) THEN 1 
    END = 1 
1

試試這個:

SELECT A 
FROM B 
WHERE 
    (CASE WHEN B.some_attr = 0 
      THEN (SELECT x FROM C WHERE B.z = z) 
      WHEN B.some_attr = 1 
      THEN (SELECT x FROM D WHERE B.z = x) 
    END) is not null 

這是假設子查詢返回一行。如果不是,只需放入max(x)而不是x。

1

我認爲這應該工作以及:

SELECT attr 
FROM SomeTable B 
WHERE EXISTS (
    SELECT 1 FROM C WHERE B.some_attr = 0 AND B.z = z UNION ALL 
    SELECT 1 FROM D WHERE B.some_attr = 1 AND B.z = x 
)