I would like to use a variable for the number of rows used in an 'OVER clause' statement. Up to now I only get it working by creation of the sql statement in a string and then execute it.
While the final purpose is to also use it in SSIS this does not work while that does not recognizes the fields in the dynamic query.
What works is:
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;
The number 7 needs to be a variable so I was trying to do something like this:
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;
This results in a syntax error at @var_MA_Low just after 'rows'.
What works is the same statement as above, but than I cannot use it as source in 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;
Has anybody an idea how to pass the number of rows as a variable into the second option?