【问题标题】:Update SQL record only if select does not return null仅当 select 不返回 null 时才更新 SQL 记录
【发布时间】:2020-07-07 17:10:46
【问题描述】:

我有一个客户及其父客户的 SQL 表,我需要在其中更新客户表以显示客户所有者(这是客户表中的另一个条目)。即客户可能以自己的权利存在,或者他们可能(可选)在同一个表中有父记录。我尝试过使用 SQL 命令

Update 
  Customers
SET
  Customers.Owner = (SELECT TOP 1 Owner from Customers Customer where CustomerId = Customers.Parent)

但是如果没有父级,这会将所有者设置为 null。如果 Select 语句不返回 null,我如何只更新记录。我尝试添加一个 where 子句,但这似乎只作用于 select 子句,而不是它的结果。

【问题讨论】:

    标签: sql select sql-update


    【解决方案1】:

    你可以使用 EXIST:

    Update 
      Customers
    SET
      Customers.Owner = (SELECT TOP 1 Owner from Customers Customer 
                         where CustomerId = Customers.Parent)
    WHERE EXIST (SELECT TOP 1 Owner from Customers Customer 
                 where CustomerId = Customers.Parent)
    

    【讨论】:

    • TOP 1EXISTS 中不需要,但无论如何都可以使用。
    【解决方案2】:

    您也可以使用MERGE 语句。

    MERGE INTO Customers tgt
    USING Customers src
    ON (src.CustomerId = tgt.Parent)
    WHEN MATCHED THEN 
    UPDATE tgt.Owner = src.Owner;
    

    【讨论】:

    • 完美——正是我想要的。谢谢。
    猜你喜欢
    • 2017-10-08
    • 2021-04-01
    • 2020-10-26
    • 2017-03-19
    • 1970-01-01
    • 2016-05-07
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多