2007/06/04

"REPLACE INTO" for SQL Server

MySQL has handy syntax which lets you look for a record by primary key and, if it exists, update its fields; otherwise insert a new record.

I wish something similar existed for SQL Server. If it does, I can't find it. But there is another way to achieve a similar effect, without too much typing:

BEGIN TRANSACTION;
DELETE FROM my_table WHERE prim_key = @prim_key_val;
INSERT INTO my_table (prim_key, other_field)
VALUES (@prim_key_val, @other_field_val);
COMMIT;

I'm probably missing something; haven't thought this through very carefully.

No comments: