Bre*_*ews 2 sql sql-server sql-server-2005 insert
我试图在表中插入数据,但如果它已经存在于表中,那么它不应该添加.
这是代码,我提出的,但它仍然添加了具有相同值的多个数据.
insert into nol_art_izm([ART_ID],[DAT])
select distinct
v.id_art, {fn now()}
from
openxml(@hDoc, '/art_kompl/nol_voac') with #vc xd
inner join nol_voac v on xd.id_art = v.id_art
where
not exists(select * from nol_art_izm where nol_art_izm.art_id=xd.id_art)
Run Code Online (Sandbox Code Playgroud)
我希望没有任何重复的"ART_ID"值
注意:此答案仅适用于SQL Server 2008 ...
使用该MERGE声明.MERGE声明的优点在于它清楚地表达了仅在没有匹配时才想要插入的意图.对于未来的读者来说,这可能会有所帮助,因为涉及INSERT .. SELECT的替代方案对于解密来说有点棘手.
-- This is where you're "merging" data into
MERGE INTO nol_art_izm dst
-- This is your merge data source
USING (
-- Use DISTINCT here, to prevent possible duplicates from the below INNER JOIN
SELECT DISTINCT v.id_art
FROM openxml(@hDoc, '/art_kompl/nol_voac') with #vc xd
INNER JOIN nol_voac v on xd.id_art = v.id_art
) src
-- This is your "join" condition, used to decide whether to perform an
-- INSERT or UPDATE
ON (dst.art_id = src.id_art)
-- When source and target don't match (see ON clause), perform an insert
WHEN NOT MATCHED THEN INSERT ([ART_ID],[DAT])
VALUES (src.id_art, {fn now()})
Run Code Online (Sandbox Code Playgroud)
本声明省略了该WHEN MATCHED THEN UPDATE条款,因为您只对表演感兴趣INSERTs,而不是UPDATEs