检查SQL中的条目NOT EXISTS

时间:2012-04-02 16:28:05

标签: sql sql-server

我正在尝试将从Excel文件导入的一个表中的数据插入到具有相同精确列的另一个表中。当我去插入所有数据时

    INSERT INTO [NQL_RawData].[dbo].[WM_MFGPNs]
    ([Manufacturer],[MPNWP],[MFGPN],[Cage],[Url],[DataSheetUrl],[Description],[Status],[NRND],[RoHS],[PbFree],[LOT],[LeadTime],[AddedOn],[AddedBy])

    SELECT [Manufacturer],dbo.BuildPNWP([MFGPN],0),[MFGPN],[Cage],[Url],[DataSheetUrl],[Description],[Status],[NRND],[RoHS],[PbFree],[LOT],[LeadTime],[AddedOn],[AddedBy]

    FROM [NQL_RawData].[dbo].[wm_BulkImport] WHERE Manufacturer = 'MFG NAME'        

它出现了此错误消息

Msg 2627,Level 14,State 1,Line 1 违反PRIMARY KEY约束'PK_MFGPNs_1'。无法在对象'dbo.WM_MFGPNs'中插入重复键。 声明已经终止。

所以我将查询更改为包含WHERE NOT EXISTS

    INSERT INTO [NQL_RawData].[dbo].[WM_MFGPNs]
    ([Manufacturer],[MPNWP],[MFGPN],[Cage],[Url],[DataSheetUrl],[Description],[Status],[NRND],[RoHS],[PbFree],[LOT],[LeadTime],[AddedOn],[AddedBy])

    SELECT [Manufacturer],dbo.BuildPNWP([MFGPN],0),[MFGPN],[Cage],[Url],[DataSheetUrl],[Description],[Status],[NRND],[RoHS],[PbFree],[LOT],[LeadTime],[AddedOn],[AddedBy]

    FROM [NQL_RawData].[dbo].[wm_BulkImport] 

    WHERE NOT EXISTS( 
    SELECT [MFGPN] 
    FROM [NQL_RawData].[dbo].[WM_MFGPNs]
    WHERE Manufacturer = 'MFG NAME'     
    )

但我仍然收到相同的错误消息。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

粗略猜测,WM_MFGPNs的PK不是制造商,而是另一列,例如MFGPN。 假设是这种情况,您的插入变为

INSERT INTO [NQL_RawData].[dbo].[WM_MFGPNs]
    ([Manufacturer],[MPNWP],[MFGPN],[Cage],[Url],[DataSheetUrl],[Description],[Status],[NRND],[RoHS],[PbFree],[LOT],[LeadTime],[AddedOn],[AddedBy])

    SELECT [Manufacturer],dbo.BuildPNWP([MFGPN],0),[MFGPN],[Cage],[Url],[DataSheetUrl],[Description],[Status],[NRND],[RoHS],[PbFree],[LOT],[LeadTime],[AddedOn],[AddedBy]

    FROM [NQL_RawData].[dbo].[wm_BulkImport] blkimp

    WHERE
       Manufacturer = 'MFG NAME' -- Your original import filter
    AND NOT EXISTS -- Prevent duplicate insertions
    ( 
    SELECT [MFGPN] 
    FROM [NQL_RawData].[dbo].[WM_MFGPNs] mfgpn
    WHERE blkimp.MFGPN = mfgpn.MFGPN
    )

编辑:好的,您的表格中有一个复合主键(即两个或多个字段的组合包含一个唯一键)。

INSERT INTO [NQL_RawData].[dbo].[WM_MFGPNs]
    ([Manufacturer],[MPNWP],[MFGPN],[Cage],[Url],[DataSheetUrl],[Description],[Status],[NRND],[RoHS],[PbFree],[LOT],[LeadTime],[AddedOn],[AddedBy])

    SELECT [Manufacturer],dbo.BuildPNWP([MFGPN],0),[MFGPN],[Cage],[Url],[DataSheetUrl],[Description],[Status],[NRND],[RoHS],[PbFree],[LOT],[LeadTime],[AddedOn],[AddedBy]

    FROM [NQL_RawData].[dbo].[wm_BulkImport] blkimp

    WHERE
       Manufacturer = 'MFG NAME' -- Your original import filter
    AND NOT EXISTS -- Prevent duplicate insertions
    ( 
    SELECT [MFGPN] 
    FROM [NQL_RawData].[dbo].[WM_MFGPNs] mfgpn
    WHERE blkimp.MFGPN = mfgpn.MFGPN
          AND blkimp.Manufacturer = mfgpn.Manufacturer
    )