How to get existence of a temporary table in sql server 2008
I wrote this query:
SELECT * INTO #nima FROM Region r
Every time I execute this queries:
SELECT OBJECT_NAME(OBJECT_ID('tempdb..#nima'))
--or
SELECT OBJECT_NAME(OBJECT_ID('#nima'))
I get NULL, but when I execute above select I 开发者_如何学Cget error that #nima alreadty exist
Try just using the OBJECT_ID function to determine if the temp table exists:
SELECT object_id('tempdb..#nima')
Or if you wish to retrieve the object name, you will need to specify the database id using the DB_ID function for the temp database:
SELECT OBJECT_NAME(OBJECT_ID('tempdb..#nima'), DB_ID('tempdb'))
This gives the internal id of #nima as expected in tempdb
SELECT OBJECT_ID('tempdb..#nima'))
OBJECT_NAME takes a local database ID. There will be no object (except by rare chance) with that ID locally because the ID comes from tempdb
Demo (untested!)
USE tempdb
SELECT OBJECT_NAME(OBJECT_ID('tempdb..#nima')) --#nima + system generated stuff
USE MyDB
SELECT OBJECT_NAME(OBJECT_ID('tempdb..#nima')) --null
-- Now we add DBID for tempdb
SELECT OBJECT_NAME(OBJECT_ID('tempdb..#nima'), 2) -- #nima + system generated stuff
精彩评论