【发布时间】:2014-03-08 07:40:21
【问题描述】:
由于某种原因,这给了我“无法在表中插入重复记录”的错误。
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 )
【问题讨论】:
-
看看你的索引
-
也许
CustomerId或DeductionCode在Deductions表或用于更新的表中是NULL。允许一个NULL,但不允许多个NULLs。 -
你的PK中有哪些列?
-
CustomerID 和 DeductionCode = 在 Deductions 表中唯一。
-
我想我发现了这个问题。发生 INSERT 时,CustomerID 为 NULL。一旦我弄清楚了,我会报告的。
标签: sql-server tsql not-exists