当存储过程完成时,将自动除去在存储过程中创建的本地临时表。由创建表的存储过程执行的所有嵌套存储过程都可以引用此表。但调用创建此表的存储过程的进程无法引用此表。所有其它本地临时表在当前会话结束时自动除去。全局临时表在创建此表的会话结束且其它任务停止对其引用时自动除去。任务与表之间的关联只在单个 Transact-SQL 语句的生存周期内保持。换言之,当创建全局临时表的会话结束时,最后一条引用此表的 Transact-SQL 语句完成后,将自动除去此表。

解决方案 »

  1.   

    if object_id('tempdb..##tmp1') is not null 
    drop table ##tmp1
      

  2.   

    if exists (select * from tempdb.dbo.sysobjects 
      where id = object_id(N'tempdb.dbo.临时表名') and
       OBJECTPROPERTY(id, N'IsUserTable') = 1)
      

  3.   

    create proc temp(@tablename varchar(200))
    as 
    declare @exec varchar(8000)
    set @exec='use tempdb
               if exists(select * from sysobjects 
                                     where id=object_id(''tempdb..'+@tablename+'''))
        print '''+@tablename+'表存在''
          else 
                          print '''+@tablename+'表不存在'''
    exec (@exec)go--测试
    create table #test(id int,name varchar(20))
    go
    temp '#test'
    go
    temp '#test1'
    -----------
    #test表存在 
    #test1表不存在
      

  4.   

    select  object_id('tempdb..##tmp1')有返回值就说明存在
      

  5.   

    if object_id('tempdb..#t') is null
    begin
     CREATE TABLE #t(id int)
     print 'not exist'
    end
    else
     print 'exist'