I need a solution for a conditional WHERE clause in SQL Server. I can’t figure out how to add the functions to the WHERE clause depending on the declared variables. I’ll bracket the conditional parts with the needed logic
DECLARE @distance bigint
DECLARE @photosneeded bigint
SET @distance * 50
SELECT * FROM users u
WHERE
[IF @distance > 0 THEN distance_function(lat1,lon1,lat2,lon2)<=@distance END]
AND
[IF @photosneeded>0 THEN u.photo IS NOT NULL AND u.photo <>'' END]
It can be done using a plain WHERE clause:
However you need to be careful with this kind of condition in the clause, because it can really screw up execution plan optimization. See @Iain’s answer for more on why.