当前位置: 代码迷 >> Sql Server >> 把表格名称作为存储过程的参数传递,求解决办法
  详细解决方案

把表格名称作为存储过程的参数传递,求解决办法

热度:87   发布时间:2016-04-27 14:50:28.0
把表格名称作为存储过程的参数传递,求解决方法
我想通过存储过程求两个表格的交集

ALTER procedure [dbo].[p_CopyData]
@SrcTableName nvarchar(50),
@DestTableName nvarchar(50)
as
begin
declare @num int,@i int
exec('select [email protected]+'.code into #t_code from [email protected]+' join [email protected]+'
on [email protected][email protected]+'.code')
end


在exec语句后,我还有针对表格#t_code的一些操作,最后该表需要被删除,经试验,exec语句中用到的表格#t_code不能在exec语句外使用
有没有什么好的解决方法?

------解决方案--------------------
改成如下面所示就行了:
SQL code
create table t1(code varchar(10))insert into t1 select 'aaa'insert into t1 select 'bbb'create table t2(code varchar(10))insert into t2 select 'bbb'gogocreate procedure [dbo].[p_CopyData]@SrcTableName nvarchar(50),@DestTableName nvarchar(50)asbegindeclare @num int,@i intexec('insert into #t_code select [email protected]+'.code from [email protected]+' join [email protected]+'on [email protected][email protected]+'.code')endgocreate table #t_code(code varchar(10))exec p_copyData 't1','t2'select * from #t_code/*code----------bbb(1 行受影响)*/godrop table t1,t2,#t_codedrop procedure p_copydata
------解决方案--------------------
存储过程内部定义的临时表的作用域只是当前这个存储过程中,临时表将在退出其作用域时由系统自动删除
------解决方案--------------------
#t_code--改为 ##t_code 全局临时表也可接收
建议
用临时表或表变量接收
  相关解决方案