{"id":8892,"date":"2022-07-18T06:31:00","date_gmt":"2022-07-18T04:31:00","guid":{"rendered":"https:\/\/expert-only.com\/?p=8892"},"modified":"2022-07-25T14:14:19","modified_gmt":"2022-07-25T12:14:19","slug":"insert-or-update-with-sql-server","status":"publish","type":"post","link":"https:\/\/expert-only.com\/en\/t-sql\/insert-or-update-with-sql-server\/","title":{"rendered":"Insert or Update with SQL Server (Upsert)"},"content":{"rendered":"\n<p>How to write an insert or update query with SQL Server, also called SQL upsert? Here are two different, quick and easy solutions to write an &#8220;UPDATE OR INSERT&#8221; query. <\/p>\n\n\n\n<p>In other words, avoid the SQL Server error &#8220;Cannot insert duplicate key in object&#8221;, &#8220;The duplicate key value is&#8221; because the row in question already exists in the target table. Indeed, inserting the same key will cause an error.<\/p>\n\n\n\n<p>Before starting, to test both solutions in a practical way, run this script to create an example table and insert two rows of data. The solution is a simple mix of an update command and an insert command.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-insert-or-update-queries-with-sql-server-to-avoid-the-unique-key-violation-error-sql-upsert\">Insert or Update queries with SQL Server to avoid the unique key violation error (SQL Upsert)<\/h2>\n\n\n\n<p>In this example, this code for creating the SALES table is used for the INSERT or UPDATE example. And therefore the update of the rows of the target table.<\/p>\n\n\n\n<p><strong><span style=\"text-decoration: underline;\">Note<\/span><\/strong>: this SQL insert or update inserts data in a very simple table, simply adjust the code to your current project.<\/p>\n\n\n\n<p>After two consecutive inserts for the same month, we got the error message below.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">-- Delete it the table if it already exists\nIF exists (\n\tSELECT 1 FROM sys.objects\n\tWHERE object_id = object_id(N'[dbo].[SALES]') \n\t\tAND type in (N'U')\n)\nBEGIN DROP TABLE [dbo].[SALES]\nEND\nGO\n\n-- Create the sample T-SQL table with the column MONTH declared as UNIQUE\nCREATE TABLE [dbo].[SALES]\n(\n\t[MONTH] nvarchar(20) UNIQUE,\n\t[AMOUNT] numeric(5)\n)\nGO\n\n-- Insert two lines of sales data for the January month as example\nINSERT INTO dbo.SALES ( MONTH, AMOUNT ) VALUES ( N'January', 1000);\nINSERT INTO dbo.SALES ( MONTH, AMOUNT ) VALUES ( N'January', 2000);\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">The error message that appears looks like this, with an English SQL Server version<\/h3>\n\n\n\n<p><strong>Msg 2627, Level 14, State 1, Line 18<br>Violation of UNIQUE KEY constraint &#8216;UQ__SALES__03EA00460E2F3BD5&#8217;. Cannot insert duplicate key in object &#8216;dbo.SALES&#8217;. The duplicate key value is (January).<br>The statement has been terminated.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Two SQL Server approaches for the UPSERT script <\/h2>\n\n\n\n<p>Indeed there are two ways or managing the SQL Server Upsert query. Very similar but simply in the opposite order.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>The first solution to make an UPSERT with Microsoft SQL Server is done in two steps<\/strong><\/h3>\n\n\n\n<p>Firstly, we test if the row to insert exists in the table, using the <a href=\"https:\/\/docs.microsoft.com\/en-us\/sql\/t-sql\/language-elements\/exists-transact-sql?view=sql-server-ver16\" target=\"_blank\" rel=\"noreferrer noopener\">EXISTS<\/a> function. <\/p>\n\n\n\n<p>Then, depending on the result, if the row exists then we perform an UPDATE to update the value, and if it does not exist then we launch an INSERT to insert a new row. <\/p>\n\n\n\n<p>In practice we don&#8217;t do an INSERT OR UPDATE, but rather an UPDATE OR INSERT.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">IF NOT EXISTS(SELECT * FROM dbo.SALES WHERE MONTH = 'January')\nBEGIN\n   INSERT INTO dbo.SALES (MONTH, AMOUNT) \n   VALUES ( N'January', 2000);\nEND\nELSE\n   BEGIN\n      UPDATE dbo.SALES\n      SET AMOUNT = 2000\n      WHERE MONTH = 'January';\n   END\nGO\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">The second solution is to UPDATE the line then count the updated rows before inserting new data<\/h3>\n\n\n\n<p>Secondly, start with an UPDATE of the row. Then, only if the number of updated rows is equal to 0 then execute the INSERT statement. <\/p>\n\n\n\n<p>Finally, the latter inserts a new row for the month of January, which is the key.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">UPDATE dbo.SALES\n   SET AMOUNT = 2000\n   WHERE MONTH = 'January';\n   \nIF @@ROWCOUNT = 0\nBEGIN\n   INSERT INTO dbo.SALES ( MONTH, AMOUNT ) \n   VALUES ( N'January', 2000);\nEND;\n<\/pre>\n\n\n\n<p>Finally, this article has presented you two ways to check the existence of data before insertion or after an update.<\/p>\n\n\n\n<p>To go further, check out these T-SQL examples to of <a href=\"https:\/\/expert-only.com\/en\/t-sql\/manage-sql-server-user-defined-functions\/\">manage SQL Server functions<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>How to write an insert or update query with SQL Server, also called SQL upsert? Here are two different, quick and easy solutions to write an &#8220;UPDATE OR INSERT&#8221; query. In other words, avoid the SQL Server error &#8220;Cannot <a class=\"mh-excerpt-more\" href=\"https:\/\/expert-only.com\/en\/t-sql\/insert-or-update-with-sql-server\/\" title=\"Insert or Update with SQL Server (Upsert)\">&#8230;<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":6139,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[454],"tags":[],"class_list":{"0":"post-8892","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-t-sql"},"_links":{"self":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/8892","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/comments?post=8892"}],"version-history":[{"count":0,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/8892\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media\/6139"}],"wp:attachment":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media?parent=8892"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/categories?post=8892"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/tags?post=8892"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}