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