日期:2014-05-18  浏览次数:20571 次

请大侠解释一下为什么出现这种情况
create   proc   sp_test1
AS
select   top   100   *   into   #tt   from   tableA
exec   sp_test2
select   *   from   #tt  
go

create   proc   sp_test2
AS
select   top   100   *,identity(int,1,1)   as   ee   into   #tt   from   tableB

select   *   from   #tt   where   ee   =   2

go


exec   sp_test1

------解决方案--------------------
没看出你具体要做什么?
------解决方案--------------------
--这样没有问题:


if object_id( 'tableA ') is not null
drop table tableA

if object_id( 'tableB ') is not null
drop table tableB
go
create table tableA(id int,ee int)
create table tableB(id int)
go

create proc sp_test2
AS
select top 100 *,identity(int,1,1) as ee into #tt from tableB

select * from #tt where ee = 2

go

create proc sp_test1
AS
select top 100 * into #tt from tableA
exec sp_test2
select * from #tt
go


exec sp_test1


drop proc sp_test1,sp_test2

drop table tableA,tableB
------解决方案--------------------
只要將兩個存儲過程中的臨時表的名稱改為不同的,也是OK的。
------解决方案--------------------

--把两个存储过程所用到的临时表改成不同就可以啦!
alter proc sp_test1
AS
select top 100 * into #t from sysobjects
exec sp_test2
select * from #t
go

create proc sp_test2
AS
select top 100 *,identity(int,1,1) as ee into #tt from syscolumns

select * from #tt where ee = 2

go


exec sp_test1

------解决方案--------------------
第一次建立时,临时表#tt已建立,同一spid未断时,是一直保留着的
你第二次 select .. Into 再#tt当然会出错了,表结构完全不一致。
(你先看一下联机帮助Select..Into 所产生的结果吧
有表存在,如要insert数据,这样是不行的
要这样 insert into table .. select..

------解决方案--------------------
/*你的代码
create proc sp_test1
AS
select top 100 * into #tt from tableA
exec sp_test2
select * from #tt
go

create proc sp_test2
AS
select top 100 *,identity(int,1,1) as ee into #tt from tableB

select * from #tt where ee = 2

go


exec sp_test1
*/
原因很简单,你的sp_test2 中的into 语句根本就没有执行,因为你在调用sp_test2之前已经在
sp_test1中生成了一个名为#tt的表了,所以才会有在sp_test2种#tt 没有ee字段的问题
不信你可以在sp_test2中加个传出的参数测试一下,在sp_test2中加一段代码:
“select top 100 *,identity(int,1,1) as ee into #tt from tableB”后面加
if @@error <> 0 return @error
检测一下是否成功执行了select top 100 *,identity(int,1,1) as ee into #tt from tableB


------解决方案--------------------
这个问题很好解释:编译执行计划时的延迟名称解析问题