如何用T-SQL语句编写将查询出来的值赋给另一个变量并查询?
要求:不用视图,不用存储过程
问题限制:因为原来有张表是临时表,而且每次创建的表明不同,我想利用sql语句将这个临时表的表名获取,赋给一个变量并查询,根据这个表名再进行修改操作
数据库为:tempdb,可以利用sysobjects中的name字段获取临时表的表名,表名以tempuf_开头,所以得到条件select name from sysobjects where name like'%tempuf_%',我想把name的值获取并查询获取的临时表中的数据。请各位高手给与指点
------解决方案--------------------
- SQL code
declare @tbname varchar(20)select @tbname from tb where id='01'exec('select * from [email protected]) --表名或字段名为变量需要用exec动态执行SQL语句
------解决方案--------------------
- SQL code
if object_id('tempdb..#tempuf_tb1') is not null drop table #tempuf_tb1gocreate table #tempuf_tb1 (id int, name varchar(10))godeclare @name varchar(max)select @name=name from tempdb..sysobjects where name like '#tempuf[_]%'exec('select * from [email protected])/*id name----------- ----------(0 行受影响)*/
------解决方案--------------------
declare @tbname varchar(100)
select @tbname=name from sysobjects where name like'%tempuf_%'
exec('select * from [[email protected]+']')
注意空格。
------解决方案--------------------
- SQL code
declare @tbname varchar(100)select @tbname=name from sysobjects where name like'%tempuf_%'exec('select * from [[email protected]+']')