Following on from my last question Sql Server query performance, and discovering that my method of allowing optional parameters in a search query is sub optimal, does anyone
In your case, the different queries would use the different indexes.
You should define a set of indexes you want to use and write an individual query for each set, replacing OR
on indexed fields with UNION ALL
:
SELECT *
FROM tables
WHERE A = @ID
AND (c.Surname = @Surname or @Surname IS NULL)
AND (HP.phonenumber = @Homphone or @Homephone IS NULL)
AND (MOB.phonenumber = @Mobile or @Mobile IS NULL)
UNION ALL
SELECT *
FROM tables
WHERE @ID IS NULL
AND c.Surname = @Surname
AND (HP.phonenumber = @Homphone or @Homephone IS NULL)
AND (MOB.phonenumber = @Mobile or @Mobile IS NULL)
UNION ALL
SELECT *
FROM tables
WHERE @ID IS NULL
AND @Surname IS NULL
AND (HP.phonenumber = @Homphone or @Homephone IS NULL)
AND (MOB.phonenumber = @Mobile or @Mobile IS NULL)