2010-09-02 78 views
0

下面的SQL代碼片段是父SQL的子選擇。SQL:如果條件結果不存在?

有沒有辦法說:「如果客戶不存在,我想運行不同的SQL」?

select orderdate, 
    (select contactname from customers where customerID = 'ALFKI' or select 'No Customer') as contactname 

from orders 

我知道這可以解決一個聯接,但主要感興趣的可能性?

+0

請發表你想,如果客戶不存在要運行什麼。 – froadie 2010-09-02 19:42:16

+0

請更新您的問題,以包含您的意思是「這可以在父SQL中作爲子選擇內聯地完成嗎?」 – 2010-09-02 19:53:15

回答

0

,你想在這裏做的東西叫做LEFT JOIN與ISNULL:

select OrderDate, isnull(c.FullName, 'No customer') CustomerName 
from Orders o 
left join Customers c on o.CustomerId = c.CustomerId 
1

例如

IF NOT EXISTS (select * from customers where customerID = 'ALFKI') 
BEGIN 
    SELECT '1' 
END 
ELSE 
BEGIN 
    SELECT '2' 
END 
+0

這可以作爲子查詢在父SQL中內聯完成嗎? – Rod 2010-09-02 19:45:00

+0

發佈更多詳情 – SQLMenace 2010-09-02 19:47:09

1

請忽略這個問題。我本來應該很疲憊,因爲這個問題聽起來讓我感到困惑。

原來我在錯誤的地方,當答案在別處。就像那樣,答案就是用優先括號解決的。對困惑感到抱歉。

杆。