子句定义中的SQL错误

时间:2013-12-30 11:42:12

标签: sql

我有一个查询,但它给了我一个无法在对象错误中插入重复键。我知道我需要包含一个不存在的语句,但无论我在哪里尝试都会出错。知道它会在哪里吗?

INSERT ProductCustomerLevel 
(
ProductID,
CustomerLevel
)
SELECT ProductID,
CustomerLevel
FROM dbo.Product p
CROSS JOIN (
        SELECT 5 AS CustomerLevel UNION ALL
        SELECT 7
        )c

2 个答案:

答案 0 :(得分:0)

让我们假设主键是(ProductID, CustomerLevel)你可以尝试类似

SELECT ProductID,
CustomerLevel
FROM dbo.Product p
CROSS JOIN (
        SELECT 5 AS CustomerLevel UNION ALL
        SELECT 7
        )c
WHERE NOT EXISTS (
                    SELECT  1
                    FROM    ProductCustomerLevel pcl
                    WHERE   p.ProductID = pcl.ProductID
                    AND     c.CustomerLevel = pcl.CustomerLevel
                )

答案 1 :(得分:0)

在运行insert之前执行此操作:

DELETE FROM ProductCustomerLevel 
WHERE CustomerLevel IN (5, 7)