表名为变量的问题!急呀

lzhzxl 2003-10-27 11:19:38
我要得到一个表的一个字段的值,但表名是变量,该怎样将查询结果赋给变量呢?
谢谢!!!
declare @id char(10),@code char(30),@TableName char(12)
select code from @TableName where id=@id
将查询的code字段值赋给变量@code!

请问该怎么做呢?谢谢
...全文
36 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengdali 2003-10-27
  • 打赏
  • 举报
回复
declare @id varchar(10),@code varchar(30),@TableName varchar(12),@sql nvarchar(4000)

set @sql='select @code=code from '+@TableName+' where id='''+@id+''''

exec sp_executesql @sql,N'@code varchar(30) output',@code output

select @code 结果
wzh1215 2003-10-27
  • 打赏
  • 举报
回复
exec('select code from '+@TableName+' where id=@id')
txlicenhe 2003-10-27
  • 打赏
  • 举报
回复
declare @id char(10),@code char(30),@TableName char(12),@sqls nvarchar(4000)

set @sqls='select @a=code from '+ @tableName + ' where id = '+@id
exec sp_executesql @sqls,N'@a char(30) output',@code output
select @code

txlicenhe 2003-10-27
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/2364/2364046.xml?temp=.829693
[交流]动态SQL语句
lzhzxl 2003-10-27
  • 打赏
  • 举报
回复
谢谢各位的帮助,现在问题解决了,非常感谢各位的热心帮助!!!
LoveSQL 2003-10-27
  • 打赏
  • 举报
回复

很简单,用动态的sql语句就可以实现了。
declare @id varchar(10),@code varchar(30),@TableName varchar(12),@sql nvarchar(4000)

set @sql='select @code=code from '+@TableName+' where id='''+@id+''''
exec sp_executesql @sql,N'@code varchar(30) output',@code output
select @code 结果

34,874

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧