Doing upsert (insert or update) in MSSQL

SQL server

In Microsoft SQL (MSSQL) there is no direct way to do upsert and there is no equivalant to ON DUPLICATE of MySql/MariaDb as it is demonstrated here: https://alexrait.blogspot.com/2022/12/doing-upsert-insert-or-update-in-mariadb.html, so we need to do it though an IF statement or an exception, here is an example:


 IF NOT EXISTS (SELECT * FROM MyTable WHERE MyKey = @MyKey)
 BEGIN
   INSERT INTO MyTable(MyKey,MyValue) VALUES (@MyKey,@MyKey)
 END
 ELSE
 BEGIN
   UPDATE MyTable SET MyValue=@MyValue WHERE MyKey=@MyKey
 END

It is still better than doing two calls to the DB, first to check if exists, then to update or insert

Post a Comment

Previous Post Next Post