2012-12-10 54 views
2

可能重複:
Select/Insert version of an Upsert: is there a design pattern for high concurrency?插入和更新在SQL Server一個查詢2005

我必須從一個表中插入數據到另一個條件的基礎上。

1.If Key is found update records 
2.If key is not found insert the record. 

我使用SQL Server 2005的所以不能用merge聲明。請建議的替代方案來實現這一

+0

建議的複製存儲過程的例子是「插入SELECT 「不是」插入/更新「 - 它絕對不是一個適當的重複鏈接。 – niico

回答

5

複製從SourceTableDesitinationTable

update dst 
set  col1 = src.col1 
from DestinationTable dst 
join SourceTable src 
on  src.Key = dst.Key 

insert DestinationTable 
     (Key, col1) 
select Key 
,  col1 
from SourceTable src 
where not exists 
     (
     select * 
     from DestinationTable dst 
     where src.Key = dst.Key 
     ) 
+0

他們是兩張桌子,而不是一張桌子。 –

+0

可能想在交易中做到這一點,但是是的 – Jodrell

+0

@MahmoudGamal,你怎麼知道這個問題呢? – Jodrell

4
IF EXISTS(--Query to check for the existence of your condition here) 
BEGIN 
    --UPDATE HERE 
END ELSE 
BEGIN 
    --INSERT HERE 
END 
+0

它會插入/更新整個表數據? –

+0

這是一個遵循的結構。您可以更新單行,幾行或整個表格。全部取決於條件 – Kaf

+0

我想檢查每個行記錄在dest中存在與否。你會如何做到這一點。我只是卡在這裏 –