关于动态表名的建立,如何查询刚新建立的表?

78hgdong 2007-05-31 11:23:37
create procedure prname
@tn varchar(40)
as
declare @tan varchar(40)
declare @tsql varchar(4000)
set @tan=tn
set @tsql='create table '+@tan+'(bid int identity(1,1),bname varchar(10),fg int)'
exec(@tsql)

select * from @tan --报错"Must declare the variable '@tan'."

为什么不能马上查询 @tan 表??? 或者怎样写? TKS!
...全文
161 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
-狙击手- 2007-05-31
  • 打赏
  • 举报
回复
create procedure prname
@tan varchar(40)
as
begin
--declare @tan varchar(40)
declare @tsql varchar(4000)
--set @tan=@tn
set @tsql='create table '+@tan+'(bid int identity(1,1),bname varchar(10),fg int)'
exec(@tsql)

exec('select * from '+ @tan )
end

go
-狙击手- 2007-05-31
  • 打赏
  • 举报
回复
不好意思, 看错了


declare @tan varchar(40)
declare @tsql varchar(4000)
set @tan='sdsd'
set @tsql='create table '+@tan+'(bid int identity(1,1),bname varchar(10),fg int)
insert '+@tan+' select ''yy'',34
'
exec(@tsql)
exec('select * from '+@tan)

/*


bid bname fg
----------- ---------- -----------
1 yy 34


*/

drop table sdsd
-狙击手- 2007-05-31
  • 打赏
  • 举报
回复
建议看看变量的有效生命期
chuifengde 2007-05-31
  • 打赏
  • 举报
回复
declare @tan varchar(40)
declare @tsql varchar(4000)
set @tan=@tn
set @tsql='create table '+@tan+'(bid int identity(1,1),bname varchar(10),fg int)
insert '+@tan+' select ''yy'',34
select * from '+@tan
exec(@tsql)
北京的雾霾天 2007-05-31
  • 打赏
  • 举报
回复
select * from @tan
-----------------
也要动态的执行才可以.

表名在Sql语句中不能使用变量.
如果要用变量就要使用exec来动态的执行语句.
78hgdong 2007-05-31
  • 打赏
  • 举报
回复
呵呵,是应用程序的参数问题,解决了,感谢三位的热情关注...

发分....
78hgdong 2007-05-31
  • 打赏
  • 举报
回复
以上三位的写法没问题,但在应用程序中执行时,@tan 新表已经建立成功,最后程序报错"list index out of bounds (0)" 这是应用程序参数报的错? 还是存储过程参数报的错?

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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