我想使用一个变量来表示“OVER 子句”语句中使用的行数。到目前为止,我只能通过在字符串中创建 sql 语句然后执行它来使其工作。
虽然最终目的是在 SSIS 中也使用它,但当它无法识别动态查询中的字段时,它不起作用。
有效的是:
select
[GUID_Fund], [Date], [Close],
avg([Close]) over (order by [GUID_Fund], [Date] rows 7 preceding) as MA_Low
from fundrates
group by [GUID_Fund], [Date], [Close]
order by [GUID_Fund] asc, [Date] desc;
数字 7 需要是一个变量,所以我试图做这样的事情:
declare @var_MA_Low as int;
select distinct @var_MA_Low = [Value1]
from Variables
where [Name]='MA_Low';
select
[GUID_Fund], [Date], [Close],
avg([Close]) over (order by [GUID_Fund], [Date] rows @var_MA_Low preceding) as MA_Low
from fundrates
group by [GUID_Fund], [Date], [Close]
order by [GUID_Fund] asc, [Date] desc;
这会导致 @var_MA_Low 在 'rows' 之后出现语法错误。
有效的是与上面相同的语句,但我不能将它用作 SSIS 中的源:
declare @MA as nvarchar(max);
declare @var_MA_Low as nvarchar(max);
select distinct @var_MA_Low = [Value1] from Variables where [Name]='MA_Low';
set @MA = N'select [GUID_Fund], [Date], [Close], avg([Close])
over (order by [GUID_Fund], [Date] rows '+@var_MA_Low+' preceding) as MA_Low
from fundrates
group by [GUID_Fund], [Date], [Close] order by [GUID_Fund] asc, [Date] desc;'
execute sp_executesql @MA;
有谁知道如何将行数作为变量传递给第二个选项?