Support our 100% FREE Projects: Donate Now OR Sponsor Now


  

sql check if record exists before insert

In this SQL Tutorial I will show how to using SQL check if record exists before insert. For to purpose of this tutorial I will use SQL Server 2008 R2 but this example should work with most versions of SQL Server.

The example below check if a row does not exists with id = -1 and if it does not exists then it inserts a row with the same ID

IF NOT EXISTS(SELECT 1

                       FROM dbo.DimDate

                       WHERE ID = -1 )

--THEN

      INSERT INTO dbo.DimDate (ID) VALUES (-1)

 

Another approach is to check if a record exists in a table and delete it and then insert new one. The advantage of this approach is that it ensure that the new row is inserted (up to date value) instead of relying on old row values

IF EXISTS(SELECT 1

                       FROM dbo.DimDate

                       WHERE ID = -1 )

--THEN

   DELETE FROM dbo.DimDate WHERE ID = -1

ELSE

   INSERT INTO dbo.DimDate (ID) VALUES (-1)

 

I hope this sql tutorial article will help you to do your own sql check if a record exists before insert.

 

Take care

Emil

Share: Share on FacebookShare on Google PlusTweet it
Comments Add Comment
No data was returned. Share your thoughts, questions and suggest improvements:
Add Comment

You found us! Below are 50 most popular searched keywords

created at TagCrowd.com

Disclaimer: While every caution has been taken to provide our readers with most accurate information and honest analysis, please use your discretion before taking any decisions based on the information in this blog. Author will not compensate you in any way whatsoever if you ever happen to suffer a loss/inconvenience/damage because of/while making use of information in this blog.