2

I have a SELECT statement that uses the result of a function multiple times. Instead of repetitively tapping the function, is there a way that I can assign a variable to it in order to make the statement more efficient and I don't have to keep tapping the function?

Overly Simplified Hypothetical Example Code:

DECLARE @Total Decimal(18,2)

SELECT t.ClientName AS Customer, t.ClientID,
--This function returns total sales for the Client
@Total = dbo.functionSalesTotal(t.ClientID), 
@Total AS Sales, (@Total * 0.13) AS Tax, 
(@Total + (@Total *0.13)) AS TotalIncludingTax
FROM table t

1 Answer 1

1

A subquery or apply is the best approach:

SELECT t.ClientName AS Customer, t.ClientID, 
       v.total AS Sales, (v.Total * 0.13) AS Tax, 
       (v.Total + (v.Total *0.13)) AS TotalIncludingTax
FROM table t CROSS APPLY
     (VALUES (dbo.functionSalesTotal(t.ClientID)) as v(total);
Sign up to request clarification or add additional context in comments.

1 Comment

Function may by deterministic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.