SQL Server Trigger to prevent duplicate inserts

Often the dba’s get requests to code triggers that prevent duplicate inserts into a sql server table. Here is the trigger script that will prevent the duplicate inserts.

Create Trigger [dbo].[Unique_Inserts_Only] on [dbo].[yourtable] INSTEAD OF INSERT
as Begin
;with cte as (select I.*, row_number() over (partition by col1, col2 order by col1orcol2oranyothercolumn) as Rownumber
from Inserted I where NOT exists
(select 1 from yourtable where I.colval = [yourtable].colval ))
INSERT INTO yourtable
 SELECT col1,col2,col3 --donot use * here use only the columns in your table because cte has multiple values like rownumber along --with columns
 from cte WHERE rownumber = 1

Hope this helps!

This entry was posted in SQL Server DBA Stuff and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s