日期:2014-05-19  浏览次数:20392 次

表变量用怎么在动态生成的sql语句中查询
下面有错误
declare   @table   table(id   int,name   nvarchar(30))
insert   into   @table  
select   1, 'a '   union   all  
select   2, 'b '   union   all  
select   3, 'c '
-----------------------
declare   @strSQL   nvarchar(100)
set   @strSQL= 'select   *   from   '+@table
exec(@strSQL)
go

------解决方案--------------------
declare @table table(id int,name nvarchar(30))
insert into @table
select 1, 'a ' union all
select 2, 'b ' union all
select 3, 'c '

select * from @table


这样不就可以了嘛
------解决方案--------------------
set @strSQL= 'select * from ' + @table

里面的@table 应该是字符变量

------解决方案--------------------
declare @strSQL nvarchar(1000)
set @strSQL= '
declare @table table(id int,name nvarchar(30))
insert into @table
select 1, ' 'a ' ' union all
select 2, ' 'b ' ' union all
select 3, ' 'c ' '

select * from @table '
exec(@strSQL)
go
------解决方案--------------------
不行,用临时表吗
------解决方案--------------------
declare @strSQL nvarchar(1000)
set @strSQL= ' '
declare @table table(id int,name nvarchar(30))
insert into @table
select 1, 'a ' union all
select 2, 'b ' union all
select 3, 'c '

select * from @table
exec(@strSQL)
go
------解决方案--------------------
@table就是表变量呀,可以直接:
select * from @table

为何要用动态sql语句呢?
如果必用动态sql的话,要写成这样:
set @str= 'select * from @table '
------解决方案--------------------
DECLARE @table
SET @table= 'SELECT * FROM ......... '
EXEC SP_EXECUTESQL @table


@table必须是 NVARCHAR TEXT NTEXT 类型
要是不好使称把命给你
------解决方案--------------------
表变量是不可以的

必须声明为临时表 create table #table1(...)