Using Multiple IF NOT EXISTS Statements Inside A Single Query
-
21-12-2019 - |
Question
I am trying to run a multi INSERT Query against MSSQL where I insert a bulk amount of records into the same table. So my query so far looks like so:
INSERT INTO [dbo].[People] (Code, Name) VALUES(101,'Bob'), (102,'John'), (103,'Jane');
I want to elaborate on the Query so that it will only INSERT the record if it doesn't already exist. I know I can use the following statement:
IF NOT EXISTS (SELECT * FROM [dbo].[People] WHERE Code = 101) BEGIN
INSERT INTO [dbo].[People] (Code, Name) VALUES(101,'Bob');
END
However, I can only work out how to apply that to a single record. Is there a way I can run multiple 'IF NOT EXISTS' statements inside a single Query?
Solution
Here's a couple of ways:
insert into [dbo].[People] (Code, Name)
select x.c, x.n
from
(
select 101 c, 'Bob' n
union select 102 c, 'Rob' n
) x
where c in (select code from [dbo].[People])
--or
insert into [dbo].[People] (Code, Name)
select x.c, x.n
from
(
select 101 c, 'Bob' n
union select 102 c, 'Rob' n
) x
where exists (select top 1 1 from [dbo].[People] p where p.code = x.c)
Or if you want to get more advanced, you could look into the merge
statement, which allows you to perform multiple operations based on a variety of conditions:
merge [dbo].[People] as target
using
(
select 101 c, 'Bob' n
union select 102 c, 'Rob' n
) as source
on source.c = target.code
when not matched by source then
insert(code,name) values (c, n);
However, for your use case merge
is probably overly complicated. That statement becomes useful when you want to do additional operations, such as update rows that exist but insert new ones where they don't.