Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to VB AndAlso in SQL?

Is there an equivalent to VB's AndAlso/OrElse and C#'s &&/|| in SQL (SQL Server 2005). I am running a select query similar to the following:

SELECT a,b,c,d
FROM table1
WHERE 
(@a IS NULL OR a = @a)
AND (@b IS NULL OR b = @b)
AND (@c IS NULL OR c = @c)
AND (@d IS NULL OR d = @d)

For example, if the "@a" parameter passed in as NULL there is no point in evaluating the 2nd part of the WHERE clause (a = @a). Is there a way to avoid this either by using special syntax or rewriting the query?

Thanks, James.

like image 632
j.strugnell Avatar asked Oct 30 '09 11:10

j.strugnell


People also ask

How can I get similar names in SQL?

To find the duplicate Names in the table, we have to follow these steps: Defining the criteria: At first, you need to define the criteria for finding the duplicate Names. You might want to search in a single column or more than that. Write the query: Then simply write the query to find the duplicate Names.

What is the opposite of like in SQL?

The NOT LIKE operator in SQL is used on a column which is of type varchar . Usually, it is used with % which is used to represent any string value, including the null character \0 .

What is the opposite of in in SQL Server?

The SQL Server NOT IN Operator will act quite the opposite of the IN. The NOT IN operator is used to restrict the number of records (or rows) returned by the SELECT Statement.

What is the opposite of like in MySQL?

In MySQL, you can use NOT LIKE to perform a negation of the LIKE operator. In other words, NOT LIKE returns the opposite result to LIKE .


2 Answers

The only way to guarantee the order of evaluation is to use CASE

WHERE
   CASE
      WHEN @a IS NULL THEN 1
      WHEN a = @a THEN 1
      ELSE 0
   END = 1
   AND /*repeat*/

In my experience this is usually slower then just letting the DB engine sort it out.

TerrorAustralis's answer is usually the best option for non-nullable columns

like image 82
gbn Avatar answered Oct 06 '22 15:10

gbn


Try this:

AND a = ISNULL(@a,a)

This function looks at @a. If it is not null it equates the expression

AND a = @a

If it is null it equates the expression

AND a = a 

(Since this is always true, it replaces the @b is null statement)

like image 23
TerrorAustralis Avatar answered Oct 06 '22 17:10

TerrorAustralis