Hi!
I tested the execution of the following procedure for SQL Server 2008 and SQL Server 2012.
USE model
GO
CREATE PROCEDURE dbo.Test
AS
BEGIN
CREATE TABLE #tempTest(id INT NOT NULL);
ALTER TABLE #tempTest ADD CONSTRAINT PK_#tempTest PRIMARY KEY(id);
DROP TABLE #tempTest;
END
GO
If I execute this procedure twice times in one transaction it fails for SQL Server 2012:
BEGIN TRANSACTION
EXEC dbo.Test
EXEC dbo.Test
ROLLBACK TRANSACTION
GO
The error message is:
Msg 2714, Level 16, State 5, Procedure Test, Line 6
There is already an object named 'PK_#tempTest' in the database.
Msg 1750, Level 16, State 0, Procedure Test, Line 6
Could not create constraint. See previous errors.
For SQL Server 2008 it works fine.
However, there is a workaround to create the primary key when creating the temporary table:
ALTER PROCEDURE dbo.Test
AS
BEGIN
CREATE TABLE #tempTest(id INT NOT NULL CONSTRAINT PK_#tempTest PRIMARY KEY);
--ALTER TABLE #tempTest ADD CONSTRAINT PK_#tempTest PRIMARY KEY(id);
DROP TABLE #tempTest;
END
GO
Does anyone have an explanation for this strange behaviour? For me it seems to be a bug.
Br
Mango81