2016-05-12 117 views
0

插入到一個表我有兩個表:更新,並從另一個

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

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

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

WHITOUT MERGE

+0

可能的重複:http://stackoverflow.com/questions/1197733/does-sql-server-offer-anything-like-mysqls-on-duplicate-key-update –

+0

您將表1合併到表2中,更新如果匹配並插入的地方不 - https://msdn.microsoft.com/en-GB/library/bb510625.aspx – MightyRearranger

+0

我不能使用合併,因爲我的數據庫是SQL SERVER 2005 –

回答

1
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語句,所以應該用caution使用..

而且我建議,使用合併爲兩個獨立的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 

原因是Paul White在這裏詳細說明answer ..

+0

爲了獲得更好的性能,首先運行'update',然後運行'insert'。 –

+0

謝謝你的建議。任何明顯的原因..或指針..? – TheGameiswar

+0

這是顯而易見的原因。如果你先插入然後你更新新插入的記錄以及;) –

0

假設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) 
    ) 
0
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); 
0

獲得了在表1中的所有行,但不是在表2

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) 

這可能是值得考慮的triggers上更新和插入,如果你想有這個手動完成

-1

在這裏,我正在寫一個腳本,當你想從table1更新table2使用完整。

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列的值。