我有 2 個 table1 和 table2 并想使用 CTE 從表 1 更新資料表 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
表 2 的預期結果
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
出現錯誤
Update or insert of view or function 'cteupdate' failed because it contains a derived or constant field.
不知道如何糾正它。謝謝
uj5u.com熱心網友回復:
當兩個表都有同名的列時,我不知道您是否能夠做到這一點(事實上,我很驚訝您沒有遇到不明確的列名錯誤)。怎么樣:
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;
- 示例db<>fiddle
我不確定為什么使用 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列應用不同的別名來解決)是您不能在 CTE 之外參考t1/ t2,因為此時剩下的就是 CTE。
- 示例db<>fiddle
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418513.html
標籤:
上一篇:取決于值的列總和
下一篇:基于特定SQL查詢創建索引
