I have an inline function which result I need multiple times during a T-SQL script execution. The results from the function are quite large. I am trying to figure out how to call the function only once.
This is my function:
CREATE OR ALTER FUNCTION getRecords (@earliestDate Datetime, @token1 varchar(64), @token2 varchar(64))
RETURNS TABLE
AS
RETURN
(
SELECT CONVERT(DATE, LogDate) AS LogDate, UserType, UserStatus
FROM LogTable WITH (NOLOCK)
WHERE UserStatus = 'Active'
AND LogDate >= @earliestDate
AND (token = @token1 OR token = @token2)
GROUP BY LogDate, UserType, UserStatus
);
GO
And I need to use the result in different places later on in the script. For instance:
DECLARE @token1 varchar(64) = '1111'
DECLARE @token2 varchar(64) = '9999'
DECLARE @earliestDate Datetime='2020-09-01';
SELECT Product, UserType,
(SELECT COUNT(DISTINCT UserStatus)
FROM getRecords (@earliestDate, @token1, @token2) AS GR
INNER JOIN mySecondTable AS ST
ON GR.UserType = ST.UserType
) AS MyCount
FROM ProductTypes INNER JOIN getRecords (@earliestDate, @token1, @token2) AS GR2
ON ProductTypes.UserType = GR2.UserType;
WHERE ProductTypes.avail = 1;
It is a long script. I need to use the results over different steps. I tried creating a temporary table but the process was too slow.
The above query works but I would like to make it more efficient.
As always, thank you for any suggestions.