临时表使用:存储过程嵌套时,均创建了相同名称的临时表.

create procedure SP_A ( @i int output )asbegin create table #t ( ta int ); insert into #t ( ta ) values ( convert(int, getdate()) ); select @i=count(0) from #t; print @i;

end;gocreate procedure SP_Basbegin create table #t ( tb int );

insert into #t ( tb ) values ( 1 ), ( 2 ), ( 3 );

declare @f int; exec dbo.SP_A @f output; select @f;

end;godeclare @a int;exec SP_A @a output;select @a;goexec SP_B;

/*------------------------

exec SP_B; ------------------------*/

(3 行受影响)消息 207,级别 16,状态 1,过程 SP_A,行 6 [批起始行 33]列名 'ta' 无效。

(1 行受影响)

---------------------------------------------------------------------------------------------------------------------

从以上信息,可以看到过程SP_A中insert into #t(ta)的时候报错,#t表中没有列名ta(此时#t应该是父过程中的#t(tb))

疑问:为什么不sp_a过程创建临时表#t的时候不报错?于是修改过程sp_a

alter procedure SP_A ( @i int output )asbegin create table #t ( ta int ); select * from #t --增加此句,查询表结构返回. insert into #t ( ta ) values ( convert(int, getdate()) ); select @i=count(0) from #t; print @i;

end;

再运行测试 :

储存过程嵌套临时表同名引发的BUG?

储存过程嵌套临时表同名引发的BUG?

可以看到此时sp_a select * from #t返回是没数据,但列名是(无列名)这个就太奇怪了.为什么这个临时表#t没有列名呢?

尝试:sp_a过程#t再增加一个字段列试试下?alter procedure SP_A ( @i int output )asbegin create table #t ( ta int ,taa int); select * from #t insert into #t ( ta ) values ( convert(int, getdate()) ); select @i=count(0) from #t; print @i;

end;go

储存过程嵌套临时表同名引发的BUG?

储存过程嵌套临时表同名引发的BUG?

运行结果和上面一样,#t还是无列名,且只有返回一列.

于是对sp_b过程#t增加两列试下?alter procedure SP_Basbegin create table #t ( tb int,tc int,td int );

insert into #t ( tb ) values ( 1 ), ( 2 ), ( 3 );

declare @f int; exec dbo.SP_A @f output; select @f;

end;go

储存过程嵌套临时表同名引发的BUG?

储存过程嵌套临时表同名引发的BUG?

奇怪的事情,此时sp_a中返回的结果还是只有一列(无列名)疑问:此时sp_a中返回的结果集的#t表到底是来自哪里呢?

看来以后存储过程如果嵌套调用,需要注意临时表的命名不能重名.

之于原因,暂时末找到,也不知道是不是bug,望各位不吝赐教,谢谢~