在插入时:子查询返回多个值

时间:2012-05-10 14:15:32

标签: sql-server sql-server-2005

我试图在表中插入所有不在xml文件中的行。如果有多行,则显示错误:“子查询返回的值超过1。当子查询跟随=,!=,=或子查询用作表达式时,不允许这样做。”这是我正在使用的查询:

insert into #tmpPievVNC
    select
        a.id, 'J'
    from
        openxml(@hDoc, '/art_kompl/nol_voav') with #vc xd 
        join nol_art a on xd.id_art = a.id
    where
            not exists(select * from nol_voav nv 
        where
            (id_art=xd.id_art) and (begDate=xd.begDate) and (endDate=xd.endDate))

如何在那里插入多行?

2 个答案:

答案 0 :(得分:0)

您可以使用连接修改sql语句以获取xml文件中不可用的记录。

以下sql语句返回nol_voav表中不在xml文件中的所有行,然后将它们插入到#tmpPievVNC表中。

insert into #tmpPievVNC
    select
        nv.id, 'J'
    from
        openxml(@hDoc, '/art_kompl/nol_voav') with #vc xd 
        inner join nol_art a on xd.id_art = a.id
    right join nol_voav nv on 
            nv.id_art=xd.id_art and nv.begDate=xd.begDate and nvendDate=xd.endDate
    where xd.id_art is null

如果您不想加入nol_art表,可以跳过"inner join nol_art a on xd.id_art = a.id"语句。

答案 1 :(得分:0)

您可以尝试将查询转换为使用LEFT JOIN:

insert into #tmpPievVNC
    select
        a.id, 'J'
    from
        openxml(@hDoc, '/art_kompl/nol_voav') with #vc xd 
        join nol_art a on xd.id_art = a.id LEFT JOIN nol_voav nv 
        on xd.id_art = nv.id_art   and xd.begDate = nv.begDate and 
        xd.endDate = nv.endDate
     WHERE nv.id_art IS NULL

这并不能解释子查询错误,但如果没有看到您正在使用的表/数据,它应该可以满足您的需求