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
x
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