SQL - 需要复制行但具有唯一的主键

时间:2015-09-28 04:14:15

标签: sql sql-server

我需要复制表中的某些行,但主键必须是唯一的。当我尝试这样做时,我得到了“违反PRIMARY KEY约束”

INSERT INTO Company.Customer
SELECT CustomerId, FirstName, LastName
FROM Company.Customer
WHERE LastName LIKE '%JONES%';

此示例中的CustomerId是主键。因此,FirstName和LastName中的值需要保持不变,但CustomerId需要更改

谢谢!

2 个答案:

答案 0 :(得分:4)

根据您的评论,似乎CustomerId不是IDENTITY列。这使事情变得棘手,因为不清楚主键是如何生成的。对于简单的情况,您可以使用这种方法:

-- Retrieve maximum value of CustomerId
DECLARE @maxid int = 0
SELECT @maxid = MAX(CustomerId) FROM Company.Customer

-- When inserting data for column CustomerId add maximum id value and row number
-- This should ensure that the key values do not clash
INSERT INTO Company.Customer (CustomerId, FirstName, LastName)
SELECT ROW_NUMBER() OVER (ORDER BY CustomerId ASC) + @maxid, FirstName, LastName 
FROM Company.Customer    
WHERE LastName LIKE '%JONES%';

但是,如果你没有理由不这样做,我建议使用IDENTITY栏 - 它会让事情变得更容易处理。

答案 1 :(得分:2)

保留主键" CustomerId"超出查询的选定部分...应该在插入的行上为您自动生成。

INSERT INTO Customer (FirstName, LastName)
(SELECT FirstName, LastName
FROM Customer
WHERE LastName LIKE '%JONES%')