2015-05-18 32 views
0

如何聲明 - 如果我的表中的字段只有NULL,則執行更新。帶有選擇值的MS SQL IF

例如:

IF customer_day_phone(從我#invoice表)where id_key = @id_key - 匹配我的參數 - is null。然後運行我的更新。

但我會有多行回來,我只想更新那些誰是NULL。

IF select customer_day_phone from #invoice where id_key = @id_key and customer_day_phone is null 
BEGIN 
... 
END 

我需要的IF語句我不能簡單地使用where day_phone是NULL,因爲它的兩部分更新。第一部分更新值,如果該字段爲空第二次更新格式化數據(但我不希望它格式化,如果它沒有更新,只有它是)。

+0

其添加到where子句'和customer_day_phone是null' – xQbert

+1

你不需要測試任何東西。只需使用where子句'和customer_day_phone爲空'來執行更新。 –

回答

1

我看不出有什麼理由不能簡單地在單個更新語句中進行兩部分更新。

只需執行以下操作。在第一次更新時更新到「格式化」值,並避免運行另一個更新語句,只是先更新它然後格式化它。

UPDATE #invoice 
SET columnName = 'value' 
WHERE customer_day_phone IS NULL --<-- this will only bring nulls 
AND id_key = @id_key 

編輯

從你的更新語句,我認爲它應該是那樣簡單.....

update a 
set a.customer_day_phone = ISNULL(b.phone,'') + ' ' + ISNULL(customer_day_phone,'') 
from #invoice a 
join T_PHONE b on a.customer_no = b.customer_no 
where b.[type] = 5 
and a.customer_day_phone IS NULL 
-- and id_key = @id_key  --<-- you had this in your first query too 
+0

我正在更新相同的字段兩次。如果customer_day_phone爲空,則更新它以將其設置爲一個值(來自另一個表上的連接)。之後,完成格式的價值看起來像一個電話#。但我不希望數據觸及/格式化,除非它已更新。因爲原始數據準確無誤。這就是我卡住的地方 – YelizavetaYR

+0

那麼這就是要點,爲什麼先更新它,然後用格式化的值更新它,爲什麼不直接將NULL值更新爲Formatted值呢?你仍然只會更新空值。 –

+0

這很公平。但我不知道該怎麼做,因爲我從另一張桌子進來了一長串字符串,而且我必須將它格式化爲看起來像電話號碼。這就是我所能做到的,但卻無法實現。這就是爲什麼我想在兩個陳述中這樣做。 'SUBSTRING(customer_day_phone,1,3)+ ' - ' + \t \t \t \t \t \t \t SUBSTRING(customer_day_phone,4,3)+ ' - ' + \t \t \t \t \t \t \t SUBSTRING(customer_day_phone,7,4) ' – YelizavetaYR

0

讓我猜測也許是這樣的事情?

Update #invoice set <fields which you want to update> WHERE id_key = @id_key and customer_day_phone is null 

而在這一點上,你不需要IF語句

+0

我確實需要發票聲明,因爲有兩部分更新。第一次更新值和第二種格式,我不想更新(重寫)你的語句將會很好,但如果它沒有更新,我也不想格式化它。 – YelizavetaYR

0

假設你想排除完全記錄更新...

UPDATE invoice SET customer_Day_Phone = @InputValue 
WHERE customer_day_Phone is null 
    and id_key = @Id_Key 

,或者如果您需要更新其他在記錄上的值,但不是電話..

UPDATE invoice SET customer_Day_Phone = case 
        when customer_Day_Phone is null then @InputValue 
        else customer_Day_phone end, 
        [email protected] 
WHERE id_key = @Id_Key