【问题标题】:Update null values by merging another table in mssql通过在 mssql 中合并另一个表来更新空值
【发布时间】:2019-07-04 07:22:03
【问题描述】:

我有两张桌子,例如:

表 1:

Customer    employee
ASD_1234    WF001
ASD_1235    WF002
ASD_1236    WF003
ASD_1237    NULL
ASD_1238    NULL
ASD_1239    NULL
ASD_1240    WF004
ASD_1234    WF001
ASD_1236    WF003
ASD_1240    WF004

表2:

Customer    com_employee
ASD_1234    WF001
ASD_1235    WF002
ASD_1236    WF003
ASD_1237    WF005
ASD_1238    WF006
ASD_1239    WF007
ASD_1240    WF004

表 2 是由唯一 Customer 组成的元数据。现在我需要通过在 Customer 上加入 table2 来更新 table1 中的 空值。我怎样才能做到这一点? 谢谢

【问题讨论】:

    标签: sql sql-server null sql-update


    【解决方案1】:

    您可以使用相关查询:

    UPDATE table1
    SET employee = (
        SELECT com_employee
        FROM table2
        WHERE table2.customer = table1.customer
    )
    WHERE employee IS NULL
    

    【讨论】:

      【解决方案2】:

      您可以使用带有 employee 可空性条件的 update-join 语句:

      UPDATE t1
      SET    t1.employee = t2.com_employee
      FROM   t1
      JOIN   t2 ON t1.customer = t2.customer
      WHERE  t1.employee IS NULL
      

      【讨论】:

        【解决方案3】:

        我们可以在这里尝试使用可更新的 CTE:

        WITH cte AS (
            SELECT t1.employee, t2.com_employee
            FROM Table1 t1
            INNER JOIN Table2 t2
                ON t1.Customer = t2.Customer
        )
        
        UPDATE cte
        SET employee = com_employee
        WHERE employee IS NULL;
        

        【讨论】:

          猜你喜欢
          • 2012-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-16
          • 2021-01-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多