Search code examples
sql-servert-sqlconditional-operator

Is there such thing as a conditional operator in SQL Server?


I have the below SQL code snippet and I want to select sales from all customers by manipulating the value of the @Customer parameter. Is there any way to do this in SQL Server 2008 R2? I've tried setting @Customer = '%' but obviously that didn't work since there is no LIKE operator.

I only want to manipulate the parameter because there will be other times where I will need to select only a single customer. Is there such a thing as using an IF/ELSE in the WHERE clause?

DECLARE @Customer varchar(5) = ''

SELECT *
FROM SalesData
WHERE Customer=@Customer

Solution

  • Is there such a thing as using an IF/ELSE in the WHERE clause

    Absolutely, there is a CASE expression - not only in the WHERE clause, but also in other parts of your query. However, a more common approach is to use logical expressions in the WHERE clause that force SQL Server to take one condition or the other depending on the parameter setting.

    my condition would be if @Customer = '' then select all

    If you would like to select all customers when the parameter is set to empty, or select all customers where the parameter is not set, you can do this:

    SELECT *
    FROM SalesData
    WHERE @Customer = ''
       OR  Customer = @Customer
    

    If @Customer is set to '', the first clause of the OR expression will be TRUE for all rows, so all customers would be returned. However, when @Customer is non-empty, the second part of the expression would be evaluated.