带有case语句的另一个表的UPDATE表

时间:2010-09-21 08:59:40

标签: sql sql-server-2005 tsql

我目前遇到了问题。我需要根据这个条件更新表B中的表A:

  • 如果表A中的一条记录为空(例如名称),则从表B
  • 更新该记录

这是我从头脑中想到的错误驱动脚本。这就是我想要发生的事情。

UPDATE TableA
   SET 
      NAME =
      (
         CASE WHEN TableA.NAME IS NULL THEN
            SELECT TableB.NAME
            FROM TableB
            WHERE TableB._ID = 1
      ),
      ADDRESS =
      (
         CASE WHEN TableA.ADDRESS IS NULL THEN
            SELECT TableB.ADDRESS
            FROM TableB
            WHERE TableB._ID = 1
      )
   WHERE TableA._ID = 1

这样的事情。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您可以将这些表连接在一起,并在表为IsNull时使用null回退到表:

update  a
set     name = IsNull(a.name, b.name)
,       address = IsNull(a.address, b.address)
from    TableA as a
inner join
        TableB as b
on      a._ID = b._ID

答案 1 :(得分:1)

试试这个 -

update a
SET a.name = ( CASE WHEN a.name IS NULL THEN b.name ELSE a.name END ),
    a.address = ( CASE WHEN a.address IS NULL THEN b.address ELSE a.address END )
FROM tableA as a, tableB as b
where a.ID = b.ID

答案 2 :(得分:1)

您可能会发现使用两个语句更容易......

UPDATE TableA
    SET NAME = (SELECT NAME
                    FROM TableB
                    WHERE TableA.ID = TableB.ID)
    WHERE NAME IS NULL;

UPDATE TableA
    SET ADDRESS = (SELECT ADDRESS
                       FROM TableB
                       WHERE TableA.ID = TableB.ID)
    WHERE ADDRESS IS NULL;