A way to check if the temporary table exists or not

Moudiz picture Moudiz · Jun 21, 2013 · Viewed 21.3k times · Source

I have this following query :

IF NOT EXISTS (SELECT 1
               FROM   sysobjects
               WHERE  id = Object_id('tempdb..TEMP_THETH_DETAILS'))
  EXECUTE (
'CREATE TABLE tempdb..TEMP_THETH_DETAILS( THETH_ID NUMERIC(5) NOT NULL, LANGUAGE VARCHAR(3) DEFAULT ''EN'' NOT NULL)'
)

GO 

The problem is the checking, it seems tempdb doesnt take on consideration if not exist, maybe because the table was create in the tempdb.
So my question is there a way I can check if the temporary table exists or not ?

Answer

Robert picture Robert · Jun 21, 2013

Try this:

IF object_id('tempdb..TEMP_THETH_DETAILS') is null
begin
   EXECUTE 
   (
       'CREATE TABLE tempdb..TEMP_THETH_DETAILS
        ( THETH_ID NUMERIC(5) NOT NULL, 
          LANGUAGE VARCHAR(3) DEFAULT ''EN'' NOT NULL
        )'
    )
end
go