我正在嘗試更新 SQL Server 中的表。帶有列(代碼,描述)的表稱為 table1。我想用 table2(code, desc) 中的唯一記錄更新 table1。table2 是 table1 的副本,但它包含 table1 中不存在的記錄。
編輯1:table1包含7月份匯出時我們ERP中的所有記錄,table2包含11月份匯出時我們ERP中的所有記錄(包括7月之后添加的記錄,這些記錄是我想添加到table1的記錄)
uj5u.com熱心網友回復:
要table1.desc使用匹配行中的值進行更新,table2只需執行以下操作:
update t1 set
t1.desc = t2.desc
from table1 t1
join table2 t2 on t2.code = t1.code;
但是,如果您想將table1僅存在于的行插入table2(如果是這種情況尚不清楚),您可以使用not exists
insert into table1 (code, desc)
select code, desc
from table2 t2
where not exists (select * from table1 t1 where t1.code = t2.code);
uj5u.com熱心網友回復:
聽起來你想要一個 INSERT
這樣的事情應該作業:
INSERT INTO table1 (code, desc)
SELECT t2.code, t2.desc
FROM table2 t2
LEFT JOIN table1 t1 on t2.code = t1.code and t1.desc = t2.desc
WHERE t1.code is null --Ignore records that already exist in table1
... 相應地調整連接子句。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/384642.html
標籤:sql sql-server
上一篇:根據時間段查找一列不同的重復行
下一篇:如何在SQL中選擇前幾年的資料?
