当前位置: 代码迷 >> Sql Server >> 查询语句中表是一个变量时,该怎样查询?解决办法
  详细解决方案

查询语句中表是一个变量时,该怎样查询?解决办法

热度:149   发布时间:2016-04-27 19:32:15.0
查询语句中表是一个变量时,该怎样查询?
CREATE PROCEDURE [dbo].[Table_Back]
@Table_Name varchar(20)
As
Begin
Declare @DocumentID varchar(30)
Declare @sql nvarchar(500)
set @sql='select @DocumentID=DocumentID from [email protected]_Name+' where id=1'
exec(@sql)
select * from JJGovOA.dbo.Office_Send where [email protected]
End
GO
有这样一个存储过程,[email protected],[email protected][email protected]录的DocumentID 字段的值呢?上面存储过程执行出现"必须声明变量 [email protected]'。"的错误.为什么呢?

------解决方案--------------------
use sp_executesql

SQL code
CREATE PROCEDURE [dbo].[Table_Back]@Table_Name varchar(20)AsBeginDeclare @DocumentID varchar(30)Declare @sql nvarchar(500)set @sql= 'select  @DocumentID=DocumentID from ' + @Table_Name + ' where id=1'exec sp_executesql @sql, [email protected] varchar(30) OUTPUT',  @DocumentID = @DocumentID OUTPUTselect * from JJGovOA.dbo.Office_Send where [email protected] End
  相关解决方案