Skip to content
Advertisement

T-SQL Conditional WHERE Clause

Found a couple of similar questions here on this, but couldn’t figure out how to apply to my scenario.

My function has a parameter called @IncludeBelow. Values are 0 or 1 (BIT).

I have this query:

If @IncludeBelow is 0, i need the query to be this:

If @IncludeBelow is 1, that last line needs to be excluded. (i.e don’t apply filter).

I’m guessing it needs to be a CASE statement, but can’t figure out the syntax.

Here’s what i’ve tried:

Obviously that’s not correct.

What’s the correct syntax?

Advertisement

Answer

I changed the query to use EXISTS because if there’s more than one location associated with a POST, there’d be duplicate POST records that’d require a DISTINCT or GROUP BY clause to get rid of…

The non-sargable

This will perform the worst of the possible solutions:

The sargable, non-dynamic version

Self explanitory….

The sargable, dynamic version (SQL Server 2005+):

Love or hate it, dynamic SQL lets you write the query once. Just be aware that sp_executesql caches the query plan, unlike EXEC in SQL Server. Highly recommend reading The Curse and Blessings of Dynamic SQL before considering dynamic SQL on SQL Server…

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement