如果不存在,如何插入

时间:2012-03-26 11:41:05

标签: 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)


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

2 个答案:

答案 0 :(得分:7)

注意:此答案仅适用于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()})

此声明省略了WHEN MATCHED THEN UPDATE条款,因为您只对执行INSERTs感兴趣,而不是UPDATEs

答案 1 :(得分:2)

尝试

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
        left join nol_art_izm n on n.art_id = v.id_art
    where n.art_id is null

<强>更新

尝试使用GROUP BY来避免重复的id_art值:

insert into nol_art_izm([ART_ID],[DAT])
    select
        v.id_art, MAX({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)
    group by v.id_art

请注意,我没有选择MAX函数来汇总{fn now()}值(如果每id_art有更多此类值)。您可能想要使用其他功能。

相关问题