This function, F_TEMP_TABLE_EXISTS, checks for the existence of a temp table (## name or # name), and returns a 1 if it exists, and returns a 0 if it doesn't exist.The script creates the function and tests it. The expected test results are also included.This was tested with SQL 2000 only.if objectproperty(object_id('dbo.F_TEMP_TABLE_EXISTS'),'IsScalarFunction') = 1 begin drop function dbo.F_TEMP_TABLE_EXISTS endgocreate function dbo.F_TEMP_TABLE_EXISTS ( @temp_table_name sysname )returns intas/*Function: F_TEMP_TABLE_EXISTS Checks for the existence of a temp table (## name or # name), and returns a 1 if it exists, and returns a 0 if it doesn't exist.*/beginif exists ( select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id( N'tempdb..'+@temp_table_name ) ) begin return 1 endreturn 0endgoprint 'Create temp tables for testing'create table #temp (x int)gocreate table ##temp2 (x int)goprint 'Test if temp tables exist'select [Table Exists] = dbo.F_TEMP_TABLE_EXISTS ( NM ), [Table Name] = NMfrom ( select nm = '#temp' union all select nm = '##temp2' union all select nm = '##temp' union all select nm = '#temp2' ) aprint 'Check if table #temp exists'if dbo.F_TEMP_TABLE_EXISTS ( '#temp' ) = 1 print '#temp exists'else print '#temp does not exist'print 'Check if table ##temp4 exists'if dbo.F_TEMP_TABLE_EXISTS ( '##temp4' ) = 1 print '##temp4 exists'else print '##temp4 does not exist'go-- Drop temp tables used for testing,-- after using function F_TEMP_TABLE_EXISTS-- to check if they exist.if dbo.F_TEMP_TABLE_EXISTS ( '#temp' ) = 1 begin print 'drop table #temp' drop table #temp endif dbo.F_TEMP_TABLE_EXISTS ( '##temp2' ) = 1 begin print 'drop table ##temp2' drop table ##temp2 end
Test Results:Create temp tables for testingTest if temp tables existTable Exists Table Name ------------ ---------- 1 #temp1 ##temp20 ##temp0 #temp2(4 row(s) affected)Check if table #temp exists#temp existsCheck if table ##temp4 exists##temp4 does not existdrop table #tempdrop table ##temp2
CODO ERGO SUM