gpt4 book ai didi

sql - 如何仅在不存在时插入

转载 作者:行者123 更新时间:2023-12-04 21:41:49 24 4
gpt4 key购买 nike

我想在表中插入数据,但如果它已经存在于表中,那么它不应该添加。
这是我想出的代码,但它仍然添加具有相同值的多个数据。

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)


我希望没有任何重复的“ART_ID”值

最佳答案

注意:此答案仅适用于 SQL Server 2008...

使用 MERGE陈述。 MERGE 语句的优点是它清楚地表达了仅在没有匹配项时才想插入的意图。对于 future 的读者,这可能会有所帮助,因为涉及 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()})

此语句省略了 WHEN MATCHED THEN UPDATE 子句,因为您只对执行 INSERTs 感兴趣,而不是 UPDATEs

关于sql - 如何仅在不存在时插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9871432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com