2

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

Rajaram Shelar
  • 7,537
  • 24
  • 66
  • 107
  • The suggested duplicate is for "Insert SELECT" not "Insert/Update" - it's definitely not an appropriate duplicate link. – niico May 02 '17 at 08:55

3 Answers3

5

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
        )
Andomar
  • 232,371
  • 49
  • 380
  • 404
5
IF EXISTS(--Query to check for the existence of your condition here)
BEGIN
  --UPDATE HERE
END ELSE
BEGIN
  --INSERT HERE
END
Kaf
  • 33,101
  • 7
  • 58
  • 78
  • Will it insert/update entire table data? – Rajaram Shelar Dec 10 '12 at 10:55
  • This is a structure to follow. You can do update a single row, a few rows or entire table. All depend on the condition – Kaf Dec 10 '12 at 10:57
  • I want to check where each row record exist in dest or not. how would you make this condition. I am just stuck here – Rajaram Shelar Dec 10 '12 at 11:21
  • Your question is already answered. Or you are not explaining the question properly. Can you show the query that you are using to check the condition? – Kaf Dec 10 '12 at 11:26
0

Here is a stored procedure example from 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
Community
  • 1
  • 1
valex
  • 23,966
  • 7
  • 43
  • 60