7

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,
    )
1

2 Answers 2

20

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...
3

Use this.

IF OBJECT_ID('tempdb.dbo.##myTempTable', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##myTempTable;
    --DROP TABLE ##tempdb.dbo.myTempTable;
    /* Above line commented out, because it generates warning:
    "Database name 'tempdb' ignored, referencing object in tempdb.",
    which is a pain in the neck if you are using a temp table to generate SQL code,
    and want to print the code to the screen.*/
END;
GO

CREATE TABLE ##myTempTable(
    FooBar nvarchar(128) not null,
);

And, in SQL Server 2016, you can write:

DROP TABLE IF EXISTS ##myTempTable
2
  • "##" does not work for me in SQL Server 2017. I need to write "tempdb..#" instead.
    – MarJer
    Jan 16, 2020 at 14:45
  • @MarJer ## is a global temp table. # is a session-scoped temp table. You can't use ## if you created a table with #, and vice versa. Also, ".." convention is tightly coupled to the executing user's default schema. Use the actual schema instead. ".." is sloppy. You should also NEVER use it in a stored procedure, because it will cause the engine to have to temporarily lock the system dictionaries to look up the current user's default schema. Always be explicit. Jan 20, 2020 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.