簡體   English   中英

從另一個表更新並插入到一個表

[英]Update and insert to one table from another

我有兩個表:

table1 :(ID,代碼,名稱)
table2 : (ID, Code, Name) 具有相同的列

我想將數據從 table1 插入到 table2 或更新 table2 中存在的列(table1.ID = table2.ID)

這樣做的簡單方法是什么?

合並

Merge table2 as target
using table1  as source
on
target.id=source.id
When matched 
Then
update 
set target.id=source.id,
    target.name=source.name
When not matched by Target Then
INSERT (id, name) VALUES (id, name);

Merge 語句存在一些問題,因此應謹慎使用..

此外,我建議使用合並作為兩個單獨的 DML 語句,如下所示..

insert into table2
select * from table1 t1 where not exists (select 1 from table2 t2 where t2.id=t1.id)

update t2
set 
t2.id=t1.id,
t2.name=t1.name
from 
table1 t1
join
table2 t2
on t1.id=t2.id

保羅懷特在他的詳細回答中陳述的原因..

MERGE table2 t2
USING table1 t1
ON t1.ID = t2.ID
WHEN MATCHED THEN
  UPDATE
  SET t2.Code = t1.Code, t2.Name = t1.Name 
WHEN NOT MATCHED BY TARGET THEN
  INSERT (ID, Name, Code)
  VALUES (t1.ID, t1.Name, t1.Code);

假設 ID 列是唯一的並且不應設置,似乎您可以在兩個 SQL 語句中完成。

/* UPDATE the rows in TABLE2 */
UPDATE TABLE2
    SET NAME = (SELECT NAME FROM TABLE1 WHERE TABLE1.CODE = TABLE2.CODE)
WHERE CODE IN (SELECT CODE FROM TABLE1)

/* INSERT the rows that are missing */
INSERT INTO TABLE2
    (CODE, NAME)
    (
         SELECT CODE, NAME
         FROM TABLE1
         WHERE CODE NOT IN (SELECT CODE FROM TABLE2)
    )

獲取在 table1 但不在 table2 中的所有行

insert into table2(id, code, name)(
SELECT table1.*
FROM table1
    LEFT JOIN table2 ON (table1.id = table2.id)
WHERE table2.C IS NULL
)

更新表2

update table2 set name = (select name from table1 where table1.code = table2.code and table1.id = table2.id)

如果您想手動完成此操作,可能值得查看更新和插入時的觸發器

源表中更新日期后將日期插入目標表這里有一個工作示例:

create table Table1(id int,name varchar(100));
create table Table2(id int,name varchar(100));
create trigger Table1Trigger after insert on Table1 for each row begin
    insert into Table2(id, name) values (new.id, new.name);
end;

使用以下查詢來驗證結果

insert into Table1 values(1,'John'),(2,'Smith'),(3,'Carol');

在這里,我正在編寫一個腳本,當您想從 table1 更新 table2 時使用 full。

    Update table2 set table2.code = table1.code, table2.name=table1.name from table1 where table2.id=table1.id

如果你想插入然后使用這個腳本。

Insert into table2  (id,code,name) select id,code,name from table1

如果在 table2 中 id 不是自動遞增的。 否則不在 table2 中插入 id 列的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM