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?
Sure – the MERGE syntax is probably the easiest. You basically need:
So it basically looks something like this:
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.