Thursday, July 19, 2012

[MSSQL] Check If Temporary Table Exists

How do you check if a temp table exists?
You can use IF OBJECT_ID('tempdb..#temp') IS NOT NULL
Let's see how it works

--Create table
USE Norhtwind
GO

CREATE TABLE #temp(id INT)

--Check if it existsIF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
  PRINT '#temp exists!'END
ELSE
BEGIN
  PRINT
'#temp does not exist!'END

--Another way to check with an undocumented optional second parameterIF OBJECT_ID('tempdb..#temp','u') IS NOT NULL
BEGIN
  PRINT '#temp exists!'END
ELSE
BEGIN
  PRINT
'#temp does not exist!'END

--Don't do this because this checks the local DB and will return does not existIF OBJECT_ID('tempdb..#temp','local') IS NOT NULL
BEGIN
PRINT '#temp exists!'END
ELSE
BEGIN
PRINT
'#temp does not exist!'END

--unless you do something like this
USE tempdb
GO

--Now it exists againIF OBJECT_ID('tempdb..#temp','local') IS NOT NULL
BEGIN
  PRINT '#temp exists!'END
ELSE
BEGIN
  PRINT
'#temp does not exist!'END

--let's go back to Norhtwind again
USE Norhtwind
GO

--Check if it existsIF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
PRINT '#temp exists!'END
ELSE
BEGIN
PRINT
'#temp does not exist!'END

now open a new window from Query Analyzer (CTRL + N) and run this code again
--Check if it existsIF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
  PRINT '#temp exists!'END
ELSE
BEGIN
  PRINT
'#temp does not exist!'END

It doesn't exist and that is correct since it's a local temp table not a global temp table

Well let's test that statement
--create a global temp table
CREATE TABLE ##temp(id INT) --Notice the 2 pound signs, that's how you create a global variable

--Check if it existsIF OBJECT_ID('tempdb..##temp') IS NOT NULL
BEGIN
  PRINT '##temp exists!'END
ELSE
BEGIN
  PRINT
'##temp does not exist!'END

It exists, right?
Now run the same code in a new Query Analyzer window (CTRL + N)

--Check if it existsIF OBJECT_ID('tempdb..##temp') IS NOT NULL
BEGIN
  PRINT '##temp exists!'END
ELSE
BEGIN
  PRINT
'##temp does not exist!'END

And yes this time it does exist since it's a global table (with ## (double-dash) as a prefix).

No comments:

Post a Comment