简体   繁体   中英

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 get 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM