I have a table:
ORG | PONumber | Code | Price
I want to SELECT all data from this table, and calculate sum of code prices for each PONumber like:
SELECT
tt1.ORG as 'Organization',
tt1.PONumber as 'PO Number',
tt1.Code as 'Code',
tt1.Price as 'Price',
'SumPrice' = FUNC001(tt1.PONumber)
FROM My_table as tt1
In this procedure I’m using function FUNC001(tt1.PONumber):
ALTER FUNCTION [dbo].[FUNC001] (@ponumber VARCHAR(MAX))
RETURNS DECIMAL AS BEGIN
DECLARE @p1 DECIMAL ;
SET @p1 = 0.0 ;
SELECT @p1 = @p1 + tt1.Price
FROM My_table as tt1
WHERE tt1.[PO number] = @ponumber
RETURN ROUND(@p1,2,1)
END
The problem is: Due my SELECT query execution this function return sum of prices each time for the same PONumbers and it takes a lot of time. Is there a way to execute this function just once for each PONumber in query and apply return value for same PONumbers? Can I use some @parameter, and check: if PONumber changed -> execute function, else select previous value?
Just try this::