当前位置: 代码迷 >> Sql Server >> 请教这样select 变量 = 变量 from 怎么查询
  详细解决方案

请教这样select 变量 = 变量 from 怎么查询

热度:320   发布时间:2016-04-27 10:57:10.0
请问这样select 变量 = 变量 from 如何查询
我想这样查询
SQL code
exec('select [email protected]+' = avg([email protected]+') from buguding')
但是不能,应该怎么改呢

------解决方案--------------------

SQL code
declare @getavg decimal(18,4),@a sysname[email protected]declare @s nvarchar(4000)set @s='select @getavg = avg([email protected]+') from buguding'exec sp_executesql @s,[email protected] decimal(18,4) output',@getavg outputselect @getavg
------解决方案--------------------
SQL code
create table test0722(id int)insert into test0722 select 10 union all select 20declare @getavg varchar(20) set @getavg='newcolname'declare @a varchar(20) set @a='id'exec('select [email protected]+' = avg([email protected]+') from test0722')/*newcolname-----------15*/
------解决方案--------------------
楼主是要得到变量值输出,不是要传入别名,那就需要用sp_executesql了
SQL code
declare @a int;declare @sql nvarchar(4000);set @a=1;SET @sql='select @b  set @[email protected]+1 select @b';exec sp_executesql @sql, [email protected] int output', @[email protected];
------解决方案--------------------
declare @aa int 
exec sp_executesql N'select @a=SUM(d) from table_1',[email protected] int out',@aa out
print @aa
按照这个模式来。。。
  相关解决方案