How to know if a temporary table already exists

1

I have an SP in which I create a temporary table in the following way:

SELECT *
INTO #TABLA_AR
FROM TRABAJADOR
WHERE AREA IN (3,5,9,15)

The SP has several processes and if it fails in some process after creating the temporary table, when correcting the error and executing it fails because the temporary table already exists

    
asked by ARR 07.11.2018 в 19:58
source

3 answers

2

All temporary tables are stored in the database called tempdb , so you should look for your temporary table there before trying to create it:

IF OBJECT_ID('tempdb..#TABLA_AR') IS NULL
BEGIN
print 'no existe'
END
ELSE
BEGIN
print 'existe'
END
    
answered by 07.11.2018 / 20:12
source
3

Use this before creating your temporary table

if (OBJECT_ID('tempdb.dbo.#TABLA_AR','U')) is not null
    drop table #TABLA_AR

This fragment validates if the temporary table already exists. If there is a delete, this way you could execute the rest of the code

    
answered by 07.11.2018 в 20:11
2

Hello I think it would be like this:

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

You put this instruction in your SP and you can recreate it, is that what you mean?

    
answered by 07.11.2018 в 20:12