出于某种原因,这给了我“无法将重复记录插入表”错误。
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 )