I've got a script that ideally would live in a view but because it creates a temp table SQL Server won't allow it.
I need to be able to call it and make joins from various stored procedures so it'd be nice to have it contained in a single spot if changes need to be made instead of embedding it all over the place. I don't think a stored procedure will work because I don't believe you can join on SP result sets.
What would work?
Here's the script:
DECLARE @fiscalPeriod smalldatetime,
@openingUnits float,
@divPrice money,
@divFactor float,
@drip float,
@endingUnits float
DECLARE divCursor CURSOR FOR
SELECT [FiscalPeriod]
,[SharePrice]
,[Rate]
FROM [dbo].[Pricing]
ORDER BY FiscalPeriod
OPEN divCursor
FETCH NEXT FROM divCursor
INTO @fiscalPeriod, @divPrice, @divFactor
SET @openingUnits = 1
SET @drip = @openingUnits/@divPrice*@divFactor
SET @endingUnits = @openingUnits + @drip
SELECT FiscalPeriod = @fiscalPeriod, OpeningUnits = @openingUnits, DivPrice = @divPrice, DivFactor = @divFactor, DRIP = @drip, EndingUnits = @openingUnits + @drip
INTO #Temp
FETCH NEXT FROM divCursor
INTO @fiscalPeriod, @divPrice, @divFactor
WHILE @@FETCH_STATUS = 0
BEGIN
SET @openingUnits = @endingUnits
SET @drip = @openingUnits/@divPrice*@divFactor
SET @endingUnits = @openingUnits + @drip
INSERT INTO #Temp (FiscalPeriod, OpeningUnits, DivPrice, DivFactor, DRIP, EndingUnits)
VALUES (@fiscalPeriod, @openingUnits, @divPrice, @divFactor, @drip, @endingUnits)
FETCH NEXT FROM divCursor
INTO @fiscalPeriod, @divPrice, @divFactor
END
CLOSE divCursor
DEALLOCATE divCursor
SELECT * FROM #Temp
DROP TABLE #Temp