Tuesday, October 14, 2008

SQL: Conditional WHERE clause

I encountered a situation that the WHERE clause in a SQL query changes based a parameter. When the parameter is '_All', there is no restriction. When the parameter is any other value, an AND section in the WHERE clause is needed.

After some digging, I found an elegant solution. Using
(@parameter = '_All' OR Field_X=@parameter). It greatly simplied the SQL query and fixed the problem of NULL value is hard to handle.

The post I saw is: http://dotnet.org.za/ilo/archive/2005/05/31/21280.aspx

No comments: