Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop temp table if it exists

Tags:

sql

sql-server

Friends,

I am creating a temp table. The script may be run several times so I need to check if the temp table exist then drop it. I have the written the code below but I get an error when running the script twice, that the table already exists:

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

It appears that IF OBJECT_ID('alarm..#lu_sensor_name_19') IS NOT NULL does not return true when the tablle is not null. What am I doing wrong?

IF OBJECT_ID('alarm..#lu_sensor_name_19') IS NOT NULL 
BEGIN 
    DROP TABLE #lu_sensor_name_19 
END

CREATE TABLE #lu_sensor_name_19(
    sensorname_id int NOT NULL,
    sensorname nvarchar(50) NOT NULL,
    paneltype_id smallint NOT NULL,
    panel_version_id int NULL,
    prefix_allowed tinyint NOT NULL,
    base_allowed tinyint NOT NULL,
    suffix_allowed tinyint NOT NULL,
    key_value int NULL,
    sort_index int NULL,
    device_allowed tinyint NOT NULL,
    sensor_name_group_id smallint NOT NULL,
    )
like image 850
Alan Ford Avatar asked Sep 17 '14 13:09

Alan Ford


People also ask

How DROP TABLE if exists?

The DROP TABLE statement deletes the specified table, and any data associated with it, from the database. The IF EXISTS clause allows the statement to succeed even if the specified tables does not exist. If the table does not exist and you do not include the IF EXISTS clause, the statement will return an error.

How do I drop a global temporary table in SQL Server if exists?

If the session where the global temporary table was created is closed, the global temporary table will be dropped automatically. Names start with a single “#” hashtag symbol. Names start with a double “##” hashtag symbol. Tables can be accessed only from the session where the table was created.

Should temp tables be dropped?

If you are wondering why it is not required to drop the temp table at the end of the stored procedure, well, it is because when the stored procedure completes execution, it automatically drops the temp table when the connection/session is dropped which was executing it.


1 Answers

Temp #Tables are created in tempdb. Try this:

IF OBJECT_ID('tempdb..#lu_sensor_name_19') IS NOT NULL 
BEGIN 
    DROP TABLE #lu_sensor_name_19 
END

CREATE TABLE #lu_sensor_name_19...

SQL Server 2016 added the ability to do the drop in one line:

DROP TABLE IF EXISTS #lu_sensor_name_19 

CREATE TABLE #lu_sensor_name_19...
like image 84
Paul Williams Avatar answered Sep 28 '22 23:09

Paul Williams