Rajaram Shelar Rajaram Shelar - 3 years ago 97
SQL Question

Insert and Update in one query in sql server 2005


Possible Duplicate:

Select / Insert version of an Upsert: is there a design pattern for high concurrency?




I have to insert data from one table to another on the basis of condition.

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


I am using sql server 2005. So can not use
merge
statement. Please suggest the alternative to achieve this

Answer Source

To copy from SourceTable to 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
        )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download