使用 CTE 更新记录

Use CTE for update records

我有 2 个 table1 和 table2,想使用 CTE

从 table 1 更新数据 table 2

table1

id name class
1 a xxx
2 b vvv
3 c eee

table2

id name class
1 a xxx
2 b
3 c

更新后 table2 的预期结果:

id name class
1 a xxx
2 b vvv
3 c eee

我的 CTE

With cteupdate as 
(Select Id, Name, class
from table1 t1
join table2 t2
on t1.Id = t2.Id)
Update cteupdate set t2.class = t1.class

Returns 这个错误:

Update or insert of view or function 'cteupdate' failed because it contains a derived or constant field.

当两个表都有同名的列时,我不知道您是否能够做到这一点(事实上,我很惊讶您没有遇到不明确的列名错误).怎么样:

UPDATE t2 SET t2.class = t1.class
  FROM dbo.table2 AS t2
  INNER JOIN dbo.table1 AS t1
  ON t1.Id = t2.Id
  WHERE t1.class IS NOT NULL;

我不确定为什么使用 CTE 如此重要,这对于未来的维护者来说可能更难理解为什么你也想要这种迂回的方法,但也许:

;WITH cteupdate AS
(
  SELECT t2.Id, t2.class, newclass = t1.class
    FROM dbo.table1 AS t1
    INNER JOIN dbo.table2 AS t2
    ON t1.Id = t2.Id
    WHERE t1.class IS NOT NULL
)
UPDATE cteupdate SET class = newclass;

主要问题(除了不明确的列名称,我通过对“新”class 列应用不同的别名来解决这个问题)是您无法引用 t1/t2 在 CTE 之外,因为此时剩下的就是 CTE。