我需要插入并检查每行是否在该表中已经存在字段“ partita_iva”,如果是,则字段“ flag”必须为1,否则必须为0。我这样做了,但是为所有行设置1,即使只是为一行设置为1
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
答案 0 :(得分:1)
答案 1 :(得分:1)
它可能可以简化。
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
答案 2 :(得分:0)
在黑暗中完全刺穿:
INSERT INTO tab2(Id,Flag)
SELECT newid, --Do you mean NEWID()?
CASE WHEN EXISTS(SELECT 1 FROM tab2 T2 WHERE T2.partita_iva = T1.partita_iva) THEN 1 ELSE 0 END
FROM tab1 T1;