2014-02-10 52 views
3

由于某种原因,这给了我“不能在表格中插入重复记录”的错误。如果记录不存在,则插入表格

INSERT INTO [DMS].[dbo].[Deductions] 
     (
     CustomerID, 
     DeductionCode, 
     DeductionDescription 
     ) 
     SELECT b.CustomerID, 
       b.AdjustmentReason, 
       b.AdjustmentReason 
     FROM @CreditDebitAdjustmentDetail b 
     WHERE NOT EXISTS (SELECT 1 
          FROM [DMS].[dbo].[Deductions] 
          WHERE CustomerID = b.CustomerID 
            AND DeductionCode = b.AdjustmentReason) 

奇怪的是,我测试了它这样:

DECLARE @CreditDebitAdjustmentDetail TABLE 
     (
     CustomerID INT, 
     AdjustmentReason VARCHAR(50) 
     ) 

INSERT INTO @CreditDebitAdjustmentDetail 
     (CustomerID, AdjustmentReason) 
VALUES (143, -- CustomerID - int 
     '024' -- AdjustmentReason - varchar(50) 
     ) 

INSERT INTO [DMS].[dbo].[Deductions] 
     (
     CustomerID, 
     DeductionCode, 
     DeductionDescription 
     ) 
     SELECT b.CustomerID, 
       b.AdjustmentReason, 
       b.AdjustmentReason 
     FROM @CreditDebitAdjustmentDetail b 
     WHERE NOT EXISTS (SELECT 1 
          FROM [DMS].[dbo].[Deductions] 
          WHERE CustomerID = b.CustomerID 
            AND DeductionCode = b.AdjustmentReason) 

,并没有插入到表,因为记录已经存在。

我在这里错过了什么吗?

编辑 - 我想我已经做这个固定的,但我仍然得到同样的错误:

INSERT INTO [DMS].[dbo].[Deductions] 
     (
     CustomerID, 
     DeductionCode, 
     DeductionDescription 
     ) 
     SELECT a.CustomerID, 
       a.AdjustmentReason, 
       a.AdjustmentReason 
     FROM @CreditDebitAdjustmentDetail a 
     WHERE NOT EXISTS (SELECT 1 
          FROM [DMS].[dbo].[Deductions] b 
          WHERE a.CustomerID = b.CustomerID 
            AND a.AdjustmentReason = b.DeductionCode) 
+0

看看你的索引 – user2615302

+1

也许'CustomerId'或'DeductionCode'是'无论是在'Deductions'表或用于表NULL'更新。允许一个“NULL”,但不允许多个“NULL”。 –

+0

你的PK有什么专栏? – twrowsell

回答

2

我想通了,DOH!

KEYWORD ...... -_- DISTINCT

INSERT INTO [DMS].[dbo].[Deductions] 
        (
        CustomerID, 
        DeductionCode, 
        DeductionDescription 
        ) 
        SELECT DISTINCT 
          a.CustomerID, 
          ISNULL(a.AdjustmentReason, 'UNKNOWN'), 
          ISNULL(a.AdjustmentReason, 'UNKNOWN') 
        FROM @CreditDebitAdjustmentDetail a 
        WHERE NOT EXISTS (SELECT 1 
             FROM [DMS].[dbo].[Deductions] b 
             WHERE a.CustomerID = b.CustomerID 
               AND CASE a.AdjustmentReason 
                 WHEN NULL THEN 'UNKNOWN' 
                 WHEN '' THEN 'UNKNOWN' 
                END = b.DeductionCode) 
相关问题