Reputation: 144
Using SQL Server 2016, I have a huge query for our Finance Dept that uses @Year
and @FinPeriod
to match up transactions with a period. And for reporting we normally pass a single value into the stored procedure. But now we are required to populate the underlying tables with the data that would normally be generated on the fly.
Is there a loop anyone can help with please? I have a temp table with year values column and a finperiod for each of those years. I am looking to loop through this table - passing in both year and period to the stored procedure, one after the other until they have all been ran.
The stored procedure element is fine for me, just getting the loop/passing part to work would be a help.
So far I have:
declare @fiscalyearid numeric(9)
declare @FiscalYear numeric(9)
declare @FiscalMonthOfYear numeric(9)
declare @Year numeric(9)
declare @FinPeriod numeric(9)
if object_id('tempdb..#dateloop','u') is not null
drop table #dateloop
select distinct
identity(int,1,1) as ID,
FiscalYear_int, FiscalMonthOfYear
into
#dateloop
from
[DW].[DDS].[dimDate]
where
FiscalYear_int = '2018'
DECLARE C CURSOR LOCAL FAST_FORWARD FOR --
SELECT
ID, FiscalYear_int, FiscalMonthOfYear
FROM
#dateloop;
OPEN C;
FETCH C INTO @FiscalYear, @FiscalMonthOfYear;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC [dbo].[Origen_Reporting->SSRS_Capex_Monitoring_Report_Expenditure] @Year, @FinPeriod
FETCH C INTO @Year,@FinPeriod
END
CLOSE C;
DEALLOCATE C;
Any tips would be brilliant. Thank you
Upvotes: 1
Views: 3281
Reputation: 1156
I guess you want your Cursor logic to work. Below is the code you can use to loop through your dates and call proc in loop.
DECLARE C CURSOR LOCAL FAST_FORWARD FOR --
SELECT
FiscalYear_int, FiscalMonthOfYear
FROM
#dateloop;
OPEN C;
Fetch next from c into @FiscalYear, @FiscalMonthOfYear
WHILE @@FETCH_STATUS = 0
BEGIN
select @FiscalYear, @FiscalMonthOfYear --exec proc passing these values
EXEC [dbo].[Origen_Reporting->SSRS_Capex_Monitoring_Report_Expenditure] @FiscalYear, @FiscalMonthOfYear
FETCH next from c INTO @FiscalYear,@FiscalMonthOfYear
END
CLOSE C;
DEALLOCATE C;
Upvotes: 3