2014-02-10 78 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) 
相關問題