I have a stored procedure which does a SELECT to return some rows. Within the SELECT, I need to check a condition in order to return the correct value for some columns. This condition consists on a scalar function. All times scalar function is called with the same parameter for the row being processed, see below:
SELECT
Id,
Name,
Surname,
CASE WHEN (dbo.GetNumTravels(Id) >= 50)
THEN 10
ELSE 99
END as Factor1,
CASE WHEN (dbo.GetNumTravels(Id) >= 50)
THEN 15
ELSE -1
END as Factor2,
CASE WHEN (dbo.GetNumTravels(Id) >= 50)
THEN 30
ELSE 70
END as Factor3
FROM
Employees
WHERE
DepartmentId = 100
I am worried about performance, I mean, I do not like to call scalar function dbo.GetNumTravels multiples times, so how to avoid this and only call it once and then used it all the times I need it?
GetNumTravelsdo and why is it slow? If you want to find each employee's travels you should be using joins or subqueries in the WHERE clause, not individual queries in the SELECT clause. You could use a view instead of a function and join it withEmployees