简体   繁体   English

如何在SQL Server 2008中获得临时表的存在

[英]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 我得到NULL,但是当我执行上面的select时,我得到#nima已经存在的错误

Try just using the OBJECT_ID function to determine if the temp table exists: 尝试仅使用OBJECT_ID函数来确定临时表是否存在:

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: 或者,如果您希望检索对象名称,则需要使用DB_ID函数为临时数据库指定数据库ID:

SELECT OBJECT_NAME(OBJECT_ID('tempdb..#nima'), DB_ID('tempdb'))

This gives the internal id of #nima as expected in tempdb 这将提供tempdb中预期的#nima内部ID

SELECT OBJECT_ID('tempdb..#nima')) 

OBJECT_NAME takes a local database ID. OBJECT_NAME使用本地数据库ID。 There will be no object (except by rare chance) with that ID locally because the ID comes from tempdb 本地不会有该ID的对象(除非偶然),因为该ID来自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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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