我把创建临时表的语句放在一个变量里面。然后用exec(@s)来执行。但是取创建不成功。
因为我要创建的临时表字段是动态的所以只能使用变量来创建(此例的字段不是动态)。
可以运行成功的
----------------------------------
--建立表
Create Table Test
(id Int,name nvarchar(20))
--插入数据Insert Test Select 1,'a'
Union all Select 1,'b'
Union all Select 2,'c'
Union all Select 3,'d'
Union all Select 4,'e'
GO
--建立存储过程
Create ProceDure P_1
As
select * from Test where id<2
GOCreate ProceDure P_2
As
select * from Test where id>2
GO
--运行
Create Table #T 
(id Int,name nvarchar(20)) 
Insert #T exec P_1
Insert #T exec P_2exec(@s)
Select * From #T
-----------------------------------
运行失败的
-----------------------------------
--建立表
Create Table Test
(id Int,name nvarchar(20))
--插入数据Insert Test Select 1,'a'
Union all Select 1,'b'
Union all Select 2,'c'
Union all Select 3,'d'
Union all Select 4,'e'
GO
--建立存储过程
Create ProceDure P_1
As
select * from Test where id<2
GOCreate ProceDure P_2
As
select * from Test where id>2
GO
--运行
declare @s nvarchar(100)
select @s='
Create Table #T
(id Int,name nvarchar(20))
Insert #T exec P_1
Insert #T exec P_2
'
exec(@s)
Select * From #TDrop Table #T
Go
--删除
Drop Table Test
Drop ProceDure P_1
Drop ProceDure P_2
-----------------------------------

解决方案 »

  1.   

    第一个最后少了清除的代码
    Drop Table #T
    Go
    --删除
    Drop Table Test
    Drop ProceDure P_1
    Drop ProceDure P_2
    另外这是第二个 的错误消息
    所影响的行数为 5 行)
    (所影响的行数为 2 行)
    (所影响的行数为 2 行)服务器: 消息 208,级别 16,状态 1,行 10
    对象名 '#T' 无效。
      

  2.   

    如果临时表用动态语句生成的话,那么它的作用域仅在Exec中有效
      

  3.   

    因为EXEC是一个的单独的连接,而临时表仅在本次连接有效,所以出了Exec就无效了
      

  4.   

    --示意代码
    可以这样访问由Exec生成的本地临时表
    Exec('Select *,Indentity(Int,1,1) As Id Into # From T1'+ '  Select * From #')---使之在一个连接中
      

  5.   

    or you can use a global temporary table ascreate ## table (........)