Create PK for #temp table failed when the script is run in parallel
I was trying to remember how to do this, but you can create a nameless primary key on a temp table and avoid this error. This is different than putting a column-level PK, as it supports more than 1 column. Here is an example:
CREATE TABLE #test
(
AccountNumber INT NOT NULL,
TransactionNumber INT NOT NULL,
PRIMARY KEY CLUSTERED (tranid, sys_process_dt)
);
This allows the end goal plus prevents name duplication. Querying will show that SQL Server will put a GUID in the name of the PK for you in sys.sysobjects:
SELECT *
FROM tempdb.sys.sysobjects
WHERE name LIKE '%#test%'
name | xtype
--------------------------------
#test___..._000000000407 | U
PK__#test_____B88A05A770B3A6A6 | PK
You can have your cake and eat it too.
I know this has been answered and accepted but still did not see the correct point has been call out.
when you create Named constraint, name of the constraint has to be precise at table level. they are scoped at database level. so either do not create named constrained and let sql pick its own name or if you give name make sure it s unique in that DB. even for TEMP DB.
This can only happen if the same client connection instantiation (which equals one SPID or connection in SQL Server) is being re-used for 2 different calls. Two parallel calls should have different connection instantiations and separate SPIDs
SPIDs are completely isolated from each other with local (single #temp tables)
Edit:
Ignore above
I've never named constraints on temp tables before. I use indexes as I need them or just add PRIMARY KEY after the column. Constraint names are database-unique in sys.objects
A PK is basically a non-unique clustered index. So use CREATE UNIQUE CLUSTERED INDEX
instead as index names are unique per table in sys.indexes.
This fails when run in 2 SSMS Query windows
CREATE TABLE #gbn (foo int NOT NULL);
ALTER TABLE #gbn ADD CONSTRAINT PK_gbn PRIMARY KEY (foo);
Msg 2714, Level 16, State 5, Line 2
There is already an object named 'PK_gbn' in the database.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors.
Curiously, the error and the constraint name match unlike your error
This works
CREATE TABLE #gbn (foo int NOT NULL);
CREATE UNIQUE CLUSTERED INDEX PK_gbn ON #gbn (foo);
- you try to insert to the same temporary table from different connections (which is impossible, instead of global temp tables),
- or you try to insert into different tables.
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