Skip to content
Advertisement

sql server – checking existence for each row in insert

I need to do an insert and check for each row if the field “partita_iva” is already in this table, if yes the field “flag” must be 1, if not then must be 0. I did this, but it set 1 for all the rows, even if should be 1 just for one row

INSERT INTO tab2(id, flag)
select newid, 
CASE 
    WHEN EXISTS(SELECT * FROM tab1 WHERE partita_iva IN(SELECT partita_iva FROM tab2))
    THEN 1
    ELSE 0
END AS flag
from tab1

Advertisement

Answer

It can probably be simplified.

INSERT INTO tab2 (id, flag)
SELECT t1.newid
, IIF(EXISTS(SELECT 1 FROM tab2 t2 WHERE t2.partita_iva = t1.partita_iva), 1, 0) AS flag
FROM tab1 t1
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement