Anatoly Lubarsky Logo
MSSQL, .NET, Design. Life and Music

T-SQL: Optional Parameters in Select Query (Using ISNULL)

Suppose, you have to make search in the database table having optional parameters. For example you have some application with advanced search UI where user does not have to fill all search criteria. We can make it with one small trick - using ISNULL function.


CREATE PROC Search
(
    @param1 INT = NULL
   ,@param2 INT = NULL
)
AS
BEGIN

   SELECT column1
     FROM table1
    WHERE column1 = ISNULL(@param1, column1)
      AND column2 = ISNULL(@param2, column2)

END

If the 1st param in ISNULL function is null - it returns 2nd parameter.


Update: syntax 2005-03-26


Related Posts:

Saturday, February 28, 2004 5:09 AM

Comments

# re: Howwould you do this - Solution

3/26/2005 10:54 PM by Bill's House O Insomnia

# re: MSSQL: Make search with optional parameters
For those from Rio Linda, the Type = NULL makes it optional
if you define the parameters with as they are required

12/27/2006 6:59 PM by GEQ

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)