2017-04-13 50 views
1

我有一個sql腳本,我想根據兩個條件更新我的表。如果傳真是空的,那麼我希望它是「N/A」,我已經在我的代碼中。第二種情況我不知道如何見面。第二種情況是,如果有傳真號碼只顯示該傳真的最後四位數字。有兩個條件的更新表

到目前爲止我的代碼是

Update Supp_copy 
Set Fax = 'N/A' 
Output 
Inserted.SupplierID, 
Inserted.Country, 
DELETED.Fax as 'Fax before update', 
INSERTED.Fax as 'Fax after update' 
From Supp_copy 
Where Fax is NULL 

我的預期產出將

SupplierID Country  Fax before update Fax after update 
---------- -------- ----------------- ---------------- 
2   USA   NULL    N/A 
3   USA   (313) 555-3349  3349 
16   USA   NULL    N/A 
19   USA   (617) 555-3389  3389 
25   Canada  NULL    N/A 
29   Canada  (514) 555-2921  2921 

我怎麼能有兩個更新或Set語句一個更新?如果我不能,我怎樣才能達到我的最終結果?

+0

哪個數據庫? – Rams

回答

1

對於SQL Server:

使用right()拿到傳真號碼的最後四個大字,內coalesce()返回'N/A'當傳真null

Update Supp_copy 
Set Fax = coalesce(right(fax,4),'N/A') 
output 
Inserted.SupplierID, 
Inserted.Country, 
DELETED.Fax as 'Fax before update', 
INSERTED.Fax as 'Fax after update' 
From Supp_copy 
+0

這是有效的,只需在SET後面的OUTPUT中進行編輯,我會將其標記爲答案。謝謝! –

+0

@ I'herehereWinterHats呃,更新。 – SqlZim

1

你可以只是substring_index函數來得到最後4位數和合並函數的空值。

Update Supp_copy 
Set Fax =coalesce(substring_index(fax,'-',-1),'N/A')