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)
看看你的索引 – user2615302
也許'CustomerId'或'DeductionCode'是'無論是在'Deductions'表或用於表NULL'更新。允許一個「NULL」,但不允許多個「NULL」。 –
你的PK有什麼專欄? – twrowsell