I have stored procedure that is creating temp table. This procedure is used to generate report in SSRS. Multiple users can use this report at the same time.
I noticed that sometimes error appears: There is already an object named 'PK_#employees' in the database.
oryginal thought was to create dynamic PK name with UUID, but it doesn't work anyway, and I don't know why.
I tried like this:
BEGIN
DECLARE @PrimaryKey NVARCHAR(200)
,@guid UNIQUEIDENTIFIER
,@sql NVARCHAR(max)
SELECT @guid = newid()
SET @PrimaryKey = CONCAT (
'PK_#employees'
,cast(@guid AS NVARCHAR(50))
)
SELECT @PrimaryKey = replace(@PrimaryKey, '-', '')
IF OBJECT_ID('tempdb..#employees_test') IS NOT NULL
DROP TABLE #employees_test;
SET @sql = 'CREATE TABLE #employees_test
(
emplid INT NOT NULL
,created_at_date DATE NOT NULL
,job_indicator CHAR(1)
,name nvarchar(255)
,CONSTRAINT ' + @PrimaryKey + ' PRIMARY KEY (emplid, created_at_date)
);'
SELECT @sql
EXECUTE (@sql)
SELECT *
FROM #employees_test
END
the EXECUTE works without error, but SELECT * FROM #employees_test
returns:
Invalid object name '#employees_test'
.
If I run created @sql manually, it works correctly. What could be problem here?
Maybe some other idea how to avoid issue with There is already an object named 'PK_#employees' in the database.
in that situation?
I am using below technique currently
IF OBJECT_ID('tempdb..#employees') IS NOT NULL
DROP TABLE #employees;
CREATE TABLE # #employees
...