SQL 在#tables 中使用 Object_id() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8401812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:33:14  来源:igfitidea点击:

using Object_id() function with #tables

sqlsql-server

提问by Alaa

I want to ensure if a temporary table exists in my database or not.

我想确保我的数据库中是否存在临时表。

I tried to use OBJECT_ID()function but it seems that I can't use it with temporary tables.

我尝试使用OBJECT_ID()函数,但似乎无法将它与临时表一起使用。

How can I resolve this problem?

我该如何解决这个问题?

回答by Martin Smith

Use

OBJECT_ID('tempdb..#foo')

to get the id for a temporary table when running in the context of another database.

在另一个数据库的上下文中运行时获取临时表的 id。

回答by Turbot

When OBJECT_ID is called, for Temporary table/Hash table TEMPDBit must be specified unless it is already working database.

当调用 OBJECT_ID 时,对于临时表/哈希表TEMPDB必须指定它,除非它已经是工作数据库。

I check in SQL2008 and verify below.

我检查了 SQL2008 并在下面进行了验证。

USE SampleDB
create table #tt1 (dummy int)
select OBJECT_ID('SampleDB..#tt1')  -- returns NULL
select OBJECT_ID('tempdb..#tt1')   -- returns ID

回答by Lieven Keersmaekers

From SQL Server Codebook

来自SQL Server 代码本

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

SQL Script

SQL 脚本

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

回答by gbn

Use this to change the context of the OBJECT_ID call to tempdb

使用它来更改对 tempdb 的 OBJECT_ID 调用的上下文

OBJECT_ID('tempdb..#table')

OBJECT_ID on MSDNshows 3 part object names. In this case you can omit schema_name

MSDN 上的OBJECT_ID显示了 3 部分对象名称。在这种情况下,您可以省略schema_name

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]