This may have been asked before, but it’s really hard to search for terms that limit the search results…
Take the following SQL snippet:
declare @source table (id int) declare @target table(id int primary key, sourceId int) set nocount on insert into @target values (0,0) insert into @source(id) values(1) --insert into @source(id) values(2) set nocount off insert into @target select (select max(id)+1 from @target), s.id from @source s select * from @target
This obviously executes without error, but now uncomment the second insert line and the following error occurs:
Msg 2627, Level 14, State 1, Line 15 Violation of PRIMARY KEY constraint 'PK__#7DB3CB72__7EA7EFAB'. Cannot insert duplicate key in object 'dbo.@target'.
I realise that the insert statement more than likely is effected against a snapshot of the @target table so (select max(id)+1 from @target) will always return a value of 1 – causing the violation error above…
Is there any way around this apart from resorting to a cursor?
Change your insert statement to the following:
This should work for this specific case but I would be careful about generalizing it.