sql 语句中的表名怎么用变量

yangcdan 2010-03-04 10:30:52
declare @mxtbname varchar(20)
set @mxtbname='fhg'


select * from @mxtbname

这样的语句该怎么实现
...全文
261 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
if object_id('tb') is not null
drop table tb
go
create table tb(id int)
insert into tb
select 1 union all
select 4 union all
select 3 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1

declare @str nvarchar(500)
declare @table nvarchar(10)
set @table='tb'
set @str='select * from '+@table
exec (@str)
yangcdan 2010-03-04
  • 打赏
  • 举报
回复
谢啦,现在可以啦
谢谢各位。。
yangcdan 2010-03-04
  • 打赏
  • 举报
回复
1的不可以
提示 必须声明变量 '@fhg'。
百年树人 2010-03-04
  • 打赏
  • 举报
回复
当表名和字段名是变量时,要用动态SQL,参考1楼
andysun88 2010-03-04
  • 打赏
  • 举报
回复
UP,晚了
中国风 2010-03-04
  • 打赏
  • 举报
回复
只可用動態
declare @mxtbname varchar(20),@s nvarchar(1000)
set @mxtbname='fhg'


set @s='select * from ['+@mxtbname+']'
exec(@s)
  • 打赏
  • 举报
回复
exec('select * from '+@mxtbname )
nianran520 2010-03-04
  • 打赏
  • 举报
回复
declare @mxtbname varchar(20) 

set @mxtbname='fhg'

exec('select * from '+ @mxtbname)

34,575

社区成员

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

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