Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a WHERE clause conditionally in SQL

Tags:

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!

like image 971
user70192 Avatar asked Jul 29 '10 15:07

user70192


People also ask

What can be the condition in WHERE clause in a SQL query?

The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.

Can WHERE clause have 2 conditions?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.

What is conditional execution in SQL?

Conditional statements are used to define what logic is to be executed based on the status of some condition being satisfied. There are two types of conditional statements supported in SQL procedures: CASE. IF.


1 Answers

SELECT
*
FROM
TaskTicket t
WHERE
 t.[UserName]=@userName 
 AND (@ID IS NULL OR t.[ID] = @ID)
like image 174
Michael Pakhantsov Avatar answered Oct 01 '22 10:10

Michael Pakhantsov