views:

23

answers:

2

Hi folks,

I've got a classic case of UPDATE or INSERTing some data into a table. I'm not sure if I should just do an UPDATE and if i get zero ROWCOUNT, then do an INSERT. Alternatively, I've heard rumours that the MERGE statement now replaces this, but I'm not sure how and if it's appropriate, in this situation.

Here's some sample sql to help demonstrate this...

ALTER PROCEDURE [dbo].[InsertLocationName]
(
    @SomeId INTEGER,
    @SomeName NVARCHAR(100)
)
AS
BEGIN
    SET NOCOUNT ON

    UPDATE TableFoo
    SET SomeName = @SomeName
    WHERE SomeId = @SomeId

    -- Did we update something?
    IF @@ROWCOUNT <= 0
        -- Nope, so add the record.
        INSERT INTO TableFoo
        VALUES (@SomeName)

END

thoughts?

+1  A: 

Sure - the MERGE syntax is probably the easiest. You basically need:

  • a target table to update
  • a source table to read from
  • a JOIN condition
  • a bunch of statement to execute for matched or non-matched rows.

So it basically looks something like this:

MERGE TableFoo as t
USING TableFooSource as s
ON t.SomeID = s.SomeID
WHEN MATCHED THEN
  UPDATE SET t.SomeName = s.SomeName
WHEN NOT MATCHED THEN
  INSERT(SomeName) VALUES(s.SomeName)
;

Don't forget the semicolon at the end!!

Marc

PS: Updated to use your table and field names. The point here is - the set of data used to be updated needs to be in a source table of its own (if needed, bulk-import that from e.g. an external file) and then the whole operation (all INSERTs and UPDATEs) are done in a single SQL statement.

marc_s
Marc, can u edit your reply using my example sql?
Pure.Krome
@Marc, so you can't have a Target table and a source table being the same thing?
Pure.Krome
nope - that won't work. You need to have the actual table which has all your data, and then you need a table with the changes to be applied
marc_s
kewl :) i'll make a table variable as the source then :)
Pure.Krome
I'd think that should work, yes!
marc_s
Sure does :) cheers mate!
Pure.Krome