Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is already an object named '#xxxx' in the database

I'm dropping/creating a temp table many times in a single script

IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims

select * into #uDims from table1

.... do something else 

IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims

select * into #uDims from table2 -- >> I get error here

.... do something else 

IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims

select * into #uDims from table3  -- >> and here

.... do something else 

when trying to run the script, I get

There is already an object named '#uDims' in the database.

on the second and third "select into..."

That is obviously a compile time error. If I run the script section by section, every thing will work well.

There are many workaround for this issue, but I want to know why SSMS is upset on that.

like image 309
FLICKER Avatar asked Oct 26 '25 14:10

FLICKER


2 Answers

You can't create the same temp table more than once inside a stored procedure.

Per the documentation (in the Remarks section),

If more than one temporary table is created inside a single stored procedure or batch, they must have different names.

So, you either have to use different temp table names or you have to do this outside a stored procedure and use GO.

like image 58
squillman Avatar answered Oct 29 '25 07:10

squillman


Ivan Starostin is correct. I test on my SQL this TSQL and it works fine.

IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims
select top 10 *  into #uDims from tblS
go 
IF OBJECT_ID('tempdb..#uDims') IS NOT NULL
DROP TABLE #uDims
select top 10 * into #uDims from Waters

without the go I get the same error as you(FLICKER).

like image 23
BobNoobGuy Avatar answered Oct 29 '25 09:10

BobNoobGuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!