SQL Server Dynamic WHERE clause without exec

By Robbe Morris
ODBC Drivers for QuickBooks, Salesforce, SAP, MSCRM, SharePoint … Free Trial!

Learn how to use SQL Server CASE statements in WHERE clauses to avoid the use of dynamic SQL.

Here's a quick little tip for searching a database based on passed in criteria that may or may not have been passed in by the user. Put the following in Query Analyzer and test it against the Pubs database with @LastName populated with or without "White". You'll find that if @LastName isn't populated, it simply looks for records with the lastname equal to itself which is always true.


use pubs

declare @LastName as nvarchar(100)

select @LastName = 'White'

select au_id,
au_fname,
au_lname
from Authors
where au_lname = case
when DataLength(@LastName) > 0 then @LastName
else au_lname
end


Submission Date:  9/23/2005 2:45:05 PM
Submitted By:  Robbe Morris
My Home Page:  http://www.robbemorris.com

Popularity  (215 Views)
Picture
Biography - Robbe Morris
Robbe has been a Microsoft MVP in C# since 2004. He is also the co-founder of EggHeadCafe.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.  Robbe also loves to scuba dive and go deep sea fishing in the Florida Keys or off the coast of Daytona Beach. Microsoft MVP