I have the following code in a stored procedure.
....
select ... into #temp from ....
alter table #temp add constraint PK_mytemp13 primary key (....)
....
And I will get the following error message from time to time if the stored procedure is run in parallel.
There is already an object named ‘PK_perf322dsf’ in the database.
Could not create constraint. See previous errors.
I think it can be avoid by the following approaches. Is there any other more elegant solution?
-
Create a temp table with primary key first. Then insert the rows.
create table #temp (... primary key (....)) -
Create PK dynamically with session id dynamically.
declare @s varchar(500) = 'alter table #temp add constraint PK_temp' + @@spid + ' primary key (....)
if 2nd – you simply may do the following – ALTER TABLE #temp ADD PRIMARY KEY(…)
if 1st – you have to create the table (regular or global temporary) with key prior to use it in parallel operations