可能重复:
Select / Insert version of an Upsert: is there a design pattern for high concurrency?
我必须根据条件将数据从一个表插入另一个表。
1.If Key is found update records
2.If key is not found insert the record.
我正在使用sql server 2005.所以不能使用merge
语句。请建议实现此目的的替代方案
答案 0 :(得分:5)
从SourceTable
复制到DesitinationTable
:
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
)
答案 1 :(得分:4)
IF EXISTS(--Query to check for the existence of your condition here)
BEGIN
--UPDATE HERE
END ELSE
BEGIN
--INSERT HERE
END
答案 2 :(得分:0)
以下是my answer to the similar question
中的存储过程示例 CREATE PROCEDURE dbo.update_table1
@Field1 int, --key1
@Field2 int, --data fields
@Field3 int,
@Field4 int
AS
SET NOCOUNT ON
update table1 set Field2=@Field2,Field3=@Field3,Field4=@Field4
where Field1=@Field1;
IF(@@Rowcount=0)
BEGIN
insert into table1(Field1,Field2,Field3,Field4)
values (@Field1,@Field2,@Field3,@Field4);
END
GO