例如下动态SQL (EXEC)语句:
DECLARE @table varchar(50) = 'table1'
DECLARE @condition varchar(500) =
DECLARE @sql varchar(3000) = '
select top 1 (PERCENTILE_DISC(0.60) WITHIN GROUP (ORDER BY [time]) OVER () ) AS [P60]
(select avg([time]) from @table) as AVG
from @table where @where
'
PRINT '2014'
SET @where = '[year]=''2014'''
SET @run = REPLACE(REPLACE(@sql, '@table', ''+@table+''), '@where', ''+@where+'')
EXEC(@run)
PRINT '2015'
SET @where = '[year]=''2015'''
SET @run = REPLACE(REPLACE(@sql, '@table', ''+@table+''), '@where', ''+@where+'')
EXEC(@run)
PRINT '2014*2+2015*3 P60'
--现在需要一个办法“保存” 2014 和 2015 年的P60的值,当所有计算(2014/2015)完毕后,总结做如下运算:2014(P60)*2 + 2015(P60)*3
这只是一个例子,问题的核心是保存动态SQL (EXEC)的结果为变量,然后调用。
------解决思路----------------------
用表变量接收语句输出的结果集,类似INSERT INTO @t EXEC (@run)。然后,再从表变量中把返回的内容读取出来,赋值给变量。
------解决思路----------------------
使用sp_executesql 即可。
------解决思路----------------------
动态执行,可以实现你想要的参数的输入和输出功能,不用让你REPLACE那样的方式不规范
你可以参考一下这边,学习下,你可以掌握得更深
http://blog.163.com/zangyunling@126/blog/static/16462450520113212357892/
如果具体地方不明,再指出来~
------解决思路----------------------
PRINT '2015'
SET @where = '[year]=''2015'''
SET @run = REPLACE(REPLACE(@sql, '@table', ''+@table+''), '@where', ''+@where+'')
EXEC sp_executesql @run, N'@a int output',@num output
//在哪里设置@a呢?
declare @num int,@result INT;
DECLARE @table varchar(50) = 'table1'
DECLARE @sql varchar(3000) = '
SET @result = select top 1 (PERCENTILE_DISC(0.60) WITHIN GROUP (ORDER BY [time]) OVER () ) AS [P60]
(select avg([time]) from @table) as AVG
from @table where @where'
PRINT '2015'
SET @where = '[year]=''2015'''
SET @run = REPLACE(REPLACE(@sql, '@table', ''+@table+''), '@where', ''+@where+'')
EXEC sp_executesql @run, N'@result AS INT OUTPUT ', @result=@num output ;
SELECT @num;