user70192 user70192 - 3 months ago 18
SQL Question

Executing a WHERE clause conditionally in SQL

I have an application on a SQL Server 2008 database. This database has a stored procedure that queries one of the tables. This stored procedure takes two parameters: userName and ID

The userName parameter will always be passed. However, the ID field will either be NULL or an actual value. If the value is something other than NULL, I need to consider it in the WHERE clause of my query. Unfortunately, I'm not positive how to do this. Currently, I'm trying

SELECT
*
FROM
TaskTicket t
WHERE
t.[UserName]=@userName AND
-- This is where I am stumped


Thank you for your help!

Answer
SELECT
*
FROM
TaskTicket t
WHERE
 t.[UserName]=@userName 
 AND (@ID IS NULL OR t.[ID] = @ID)
Comments