MS SQL IF 具有 select 值

MS SQL IF with a select value

我该如何声明 - 如果我的 table 中的某个字段为 NULL,则仅进行更新。

例如:

IF customer_day_phone(来自我的 #invoice table)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 语句,我不能简单地在 day_phone 为 NULL 的地方使用,因为它分为两部分更新。如果字段为 null,则第一部分更新值,第二部分更新格式化数据(但我不希望它格式化,如果它没有更新,只有当它被更新时)。

让我猜猜可能是这样的?

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

此时您不需要 IF 语句

假设您想完全排除记录更新...

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

或者如果您需要更新记录中的其他值而不是 phone..

UPDATE invoice SET customer_Day_Phone = case 
                   when customer_Day_Phone  is null then @InputValue 
                   else customer_Day_phone end,
                   field2=@field2value
WHERE id_key = @Id_Key

我看不出有什么理由不能在单个更新语句中简单地执行两部分更新。

只需执行以下操作。在第一次更新时更新到 "Formatted" 值并避免 运行 另一个更新语句,只是先更新它然后格式化它。

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