> Is there an alternative for case statements?
Sure, one trick I learned here and have adopted is for things like positive
INTegers, you can help the optimizer choose a seek instead of a scan by
doing something like this:
CREATE PROCEDURE dbo.foo
@value INT = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT col1,col2,col3 FROM table
WHERE value >= COALESCE(@value, 0)
AND value <= COALESCE(@value, 2147483647);
END
GO
This way, if you have an index on the column 'value', you aren't hurt as
much by optional parameters, as opposed to this case, which is much more
likely to cause a scan and slow down your query:
WHERE value = COALESCE(@value, value);
...which is essentially shorthand for:
WHERE value = CASE WHEN @value IS NULL THEN value ELSE @value END;
Of course, when you have multiple ways of getting something done, you should
always test performance *in your environment* and *against your data.* It
is very difficult for any of us to give you a straight answer about which
way is faster unless we have a very comprehensive understanding of your
hardware, data model and usage.
I am not even clear exactly how you intend to use case in all scenarios, but
I will say that there is often an alternative, and I will state again that
there is no clear-cut answer that option a is better than option b in all
cases. This is something you learn over time, with experience, and by
testing every time you change anything.
>> Stay informed about: Using Case Conditions in WHERE clause