Can I use the MERGE statement in SQL Server 2005?

后端 未结 1 1681
刺人心
刺人心 2020-11-30 09:32

I am using SQL Server 2005 and I wanted to create MERGE statement or concept in single query in SQL Server 2005. Is it possible?

相关标签:
1条回答
  • 2020-11-30 09:33

    MERGE was introduced in SQL Server 2008. If you want to use that syntax, you'll need to upgrade.

    Otherwise, the typical approach will depend on where the source data is from. If it's just one row and you don't know if you need to update or insert, you'd probably do:

    UPDATE ... WHERE key = @key;
    
    IF @@ROWCOUNT = 0
    BEGIN
        INSERT ...
    END
    

    If your source is a #temp table, table variable, TVP or other table, you can do:

    UPDATE dest SET ...
      FROM dbo.destination AS dest
      INNER JOIN dbo.source AS src
      ON dest.key = src.key;
    
    INSERT dbo.destination SELECT ... FROM dbo.source AS src
      WHERE NOT EXISTS (SELECT 1 FROM dbo.destination WHERE key = src.key);
    

    As with MERGE (and as Michael Swart demonstrated here), you will still want to surround any of these methods with proper transactions, error handling and isolation level to behave like a true, single operation. Even a single MERGE statement does not protect you from concurrency.

    I've published some other cautions about MERGE in more detail here.

    0 讨论(0)
提交回复
热议问题