存储过程中新建临时表的

要写一个存储过程,如果临时表 test 不存在 ,新建临时表,如果存在不新建

 

alter procedure test
as
    if object_id('tempdb..#test') is null
        begin
            print '不存在'
            create table #test (
                number int not null primary key,
                message varchar(50) not null
            )
        end
else
    print '存在'

 

exec test
select * from #test

上面的SQL语句,调用存储过程之后查询临时表会报错

不存在
消息 2714,级别 16,状态 6,过程 test,第 6 行
数据库中已存在名为 '##test' 的对象。

后来将 #test 改为 ##test  便可以了

猜想可能是在存储过程中创建的 #test 只能在存储过程中写查询可以查询到 ##表示全局临时表,在存储过程外也可以查询到

 

posted @ 2019-04-26 10:45  正月雨  阅读(4608)  评论(0编辑  收藏  举报