我有两个表,我需要将数据从SRCServiceUsers复制到客户端
每次我运行它都会得到以下结果:
违反PRIMARY KEY约束 'PK_Clients'。无法插入重复 对象'dbo.Clients'中的键。该 声明已经终止。该 主键ClientId字段不是 身份栏因此需要 填充
到目前为止,我有以下
insert into Clients(ClientID, Title, Forenames, FamilyName,
[Address], Town, County, PostCode,
PhoneNumber, StartDate)
SELECT (Select Max(Clients.ClientID)+ 1,
SRCServiceUsers.Title,
SRCServiceUsers.[First Names],
SRCServiceUsers.Surname,
--BUILD UP MUITIPLE COLUMNS
SRCServiceUsers.[Property Name] + ', ' + SRCServiceUsers.Street + ', '
+ SRCServiceUsers.Suburb as [Address],
SRCServiceUsers.Town,
SRCServiceUsers.County,
SRCServiceUsers.Postcode,
SRCServiceUsers.Telephone,
SRCServiceUsers.[Start Date]
FROM
srcsERVICEuSERS
如何在插入数据时自动增加PK字段 - CLientID?
非常感谢
安德鲁
答案 0 :(得分:3)
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
DECLARE @MaxClientId INT
SELECT @MaxClientId = MAX(ClientID) /*SERIALIZABLE will prevent any inserts above this*/
FROM Clients
INSERT INTO Clients(....)
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) + @MaxClientId...
FROM srcsERVICEuSERS
COMMIT