从诱惑表插入SEQ_NUM <> 2

时间:2019-04-02 20:11:43

标签: sql sql-server sql-server-2014

我正在尝试从临时表中的数据插入下表PS_VNDR_ADDR_SCROL中,而其中插入的表PS_VNDR_ADDR_SCROL中没有一行具有SEQ_NUM的行对于相同的2等于VENDOR_ID

下面的SQL运行,但是不插入任何行,我知道应该有132个满足此条件的记录。

INSERT PS_VNDR_ADDR_SCROL 
SELECT 'SHARE', A.VENDOR_ID, 2, 'HOME', 'BUSN', ''
FROM #DepWork2 A
WHERE NOT EXISTS (
    SELECT VENDOR_ID 
    FROM PS_VNDR_ADDR_SCROL B 
    WHERE B.VENDOR_ID = A.VENDOR_ID AND SEQ_NUM <> 2
)

我也使用NOT IN进行了如下尝试,但是出现语法错误:

INSERT PS_VNDR_ADDR_SCROL 
SELECT 'SHARE', A.VENDOR_ID, 2, 'HOME', 'BUSN', ''
FROM #DepWork2 A
WHERE NOT IN (
    SELECT VENDOR_ID 
    FROM PS_VNDR_ADDR_SCROL B 
    WHERE B.VENDOR_ID = A.VENDOR_ID AND SEQ_NUM <> 2
)

2 个答案:

答案 0 :(得分:1)

  

插入下表PS_VNDR_ADDR_SCROL [...]中,其中[strong] 表中已经存在 1}}等于2,代表相同的PS_VNDR_ADDR_SCROL

您使用SEQ_NUM的方法看起来不错,但是我认为,为了符合您的规范,相关子查询应拼写为:

VENDOR_ID

代替:

NOT EXISTS

因此,请尝试:

SELECT VENDOR_ID 
FROM PS_VNDR_ADDR_SCROL B 
WHERE B.VENDOR_ID = A.VENDOR_ID AND SEQ_NUM = 2

注意:第二个查询中的语法错误来自SQL代码的这一部分:

SELECT VENDOR_ID 
FROM PS_VNDR_ADDR_SCROL B 
WHERE B.VENDOR_ID = A.VENDOR_ID AND SEQ_NUM <> 2

您需要在INSERT PS_VNDR_ADDR_SCROL SELECT 'SHARE', A.VENDOR_ID, 2, 'HOME', 'BUSN', '' FROM #DepWork2 A WHERE NOT EXISTS ( SELECT 1 FROM PS_VNDR_ADDR_SCROL B WHERE B.VENDOR_ID = A.VENDOR_ID AND SEQ_NUM = 2 ) 条件的左侧指定一列。可能应该是:

...
WHERE NOT IN (
    SELECT VENDOR_ID 
    ...
)

注意:当然,第二个查询在相关子查询中也应具有条件NOT IN而不是... WHERE A.VENDOR_ID NOT IN ( SELECT VENDOR_ID ... )

答案 1 :(得分:0)

使用存在尝试

INSERT PS_VNDR_ADDR_SCROL 
SELECT 'SHARE', A.VENDOR_ID, 2, 'HOME', 'BUSN', ''
FROM #DepWork2 A
WHERE  EXISTS (SELECT 1  FROM PS_VNDR_ADDR_SCROL B  WHERE B.VENDOR_ID = A.VENDOR_ID AND SEQ_NUM = 2)