using Object_id() function with #tables

前端 未结 4 1567
醉话见心
醉话见心 2020-12-11 00:51

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

相关标签:
4条回答
  • 2020-12-11 00:57

    Use

    OBJECT_ID('tempdb..#foo')
    

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

    0 讨论(0)
  • 2020-12-11 01:02

    From SQL Server Codebook

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

    SQL Script

    --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
    
    0 讨论(0)
  • 2020-12-11 01:03

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

    OBJECT_ID('tempdb..#table')
    

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

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

    0 讨论(0)
  • 2020-12-11 01:16

    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
    
    0 讨论(0)
提交回复
热议问题