使用条件连接的Sql Server更新

时间:2013-08-14 14:48:36

标签: sql-server

我正在寻找一种方法将这两个语句组合成SQL服务器中的一个。我试着搜索"条件连接"但是没有看到这个确切的例子谢谢你的帮助。

update
    employees
set
    employees.RefID = ed.RefID
from
    #tmpEmployees employees 
    inner join EmployeeDirectory ed on ed.ABC = employees.ABC
where
    ( nullif(ed.ABC, '') is not null and  nullif(employees.ABC, '') is not null)



update
    employees
set
    employees.RefID = ed.RefID
from
    #tmpEmployees employees 
    inner join EmployeeDirectory ed on ed.DEF = employees.DEF
where
    ( nullif(ed.DEF, '') is not null and  nullif(employees.DEF, '') is not null)

2 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解你要完成的任务,但也许以下内容会有所帮助:

UPDATE
    employees
SET
    employees.RefID = ed.RefID
FROM
    #tmpEmployees employees 
JOIN EmployeeDirectory ed 
  ON ed.ABC = employees.ABC OR
     ed.ABC IS NULL AND employees.ABC IS NULL OR
     ed.DEF = employees.DEF OR
     ed.DEF IS NULL AND employees.DEF IS NULL

如果NULL值处理不是您想要的(或与您想要的相反),您可以修改/反转它。

答案 1 :(得分:0)

尝试

UPDATE e
   SET e.RefID = d.RefID
  FROM #tmpEmployees e JOIN EmployeeDirectory d 
    ON e.ABC = d.ABC OR e.DEF = d.DEF
 WHERE NULLIF(e.ABC, '') IS NOT NULL 
   AND NULLIF(d.ABC, '') IS NOT NULL
   AND NULLIF(d.DEF, '') IS NOT NULL
   AND NULLIF(e.DEF, '') IS NOT NULL

UPDATE e
   SET e.RefID = COALEASCE(d1.RefID, d2.RefID)
  FROM #tmpEmployees e LEFT JOIN EmployeeDirectory d1 
    ON e.ABC = d1.ABC LEFT JOIN EmployeeDirectory d2 
    ON e.DEF = d2.DEF