user3575799
user3575799

Reputation: 41

Need help to get an insert statement in SQL Server

I would need to insert the non existing values to a Table.

Sample data in the table

ProductSubGroupID
-----------------
F11WD
F77AH
G36CN
G37HJ
H11AA
H11AD

Now I need to insert the non existing values in the table.

Values want to be checked and inserted.

H11AA
H11AD
G78DE
G76DK
G41JA
B45JC

Query written

insert into BarcodeSubgroup 
   select 
       productsubgroupid 
   where 
       not exists ('G78DE', 'G76DK', 'G41JA',
                   'B45JC', 'H11AA', 'H11AD')

Now it should insert only the 4 non existing values.

Upvotes: 0

Views: 66

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269463

You can do this with select . . . not exists:

insert into BarcodeSubgroup(productsubgroupid)
    select productsubgroupid 
    from (values ('G78DE'), ('G76DK'), ('G41JA'), ('B45JC'), ('H11AA'), ('H11AD') ) v(productsubgroupid)
    where not exists (select 1
                      from BarcodeSubgroup bs
                      where bs.productsubgroupid = v.productsubgroupid
                     );

Upvotes: 2

Related Questions