Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Object_id() function with #tables

Tags:

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.

How can I resolve this problem?

like image 697
Alaa Avatar asked Dec 06 '11 14:12

Alaa


People also ask

What is Object_id function in SQL?

T-SQL OBJECT_ID() metadata function This function returns the database object ID number of a schema object and returns NULL on error. These objects can be tables, views, constraints or stored procedures etc.

How do I find the table name using the object ID in SQL Server?

objects catalog view for the object specified by OBJECT_NAME in the WHERE clause of the SELECT statement. (Your object number (274100017 in the example below) will be different. To test this example, look up a valid object number by executing SELECT name, object_id FROM sys. objects; in your database.)

How do I get all database objects in SQL Server?

Use SQL Server Management StudioIn Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance. To see a list of all databases on the instance, expand Databases.

How do I find the database ID in SQL Server?

Return the ID of the current database. This example returns the database ID of the current database. SELECT DB_ID();


2 Answers

Use

OBJECT_ID('tempdb..#foo') 

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

like image 175
Martin Smith Avatar answered Oct 22 '22 19:10

Martin Smith


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

I check in SQL2008 and verify below.

USE SampleDB create table #tt1 (dummy int) select OBJECT_ID('SampleDB..#tt1')  -- returns NULL select OBJECT_ID('tempdb..#tt1')   -- returns ID 
like image 34
Turbot Avatar answered Oct 22 '22 20:10

Turbot