StasGL
StasGL

Reputation: 59

Check for duplicate with same id before insert in SQL Server

I need update script where I must check before insert if there is the same row with the same code.

INSERT INTO Customers (UnicCode, CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('W5RTS', 'Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

How I can implement to this query select from Customers and if there is no such record to add new?

Upvotes: 0

Views: 795

Answers (2)

Suraj Kumar
Suraj Kumar

Reputation: 5643

You can just try not exists as shown below

if not exists (select 1 from Customers where UnicCode = 'W5RTS')
begin
   --Your insert logic/statements here
end
else
begin
  --Your update or other logic/statements here
end

Upvotes: 2

allmhuran
allmhuran

Reputation: 4454

exists is a very self-explanatory way to check for existence

insert into Customers
(
   UnicCode,
   CustomerName,
   ContactName,
   Address,
   City,
   PostalCode,
   Country
)
select   'W5RTS',
         'Cardinal',
         'Tom B. Erichsen',
         'Skagen 21',
         'Stavanger',
         '4006',
         'Norway'
where not exists
(
   select * from Customers where UnicCode = 'W5RTS'
);

Upvotes: 2

Related Questions