[sql] CASE in WHERE, SQL Server

I'm doing some search, where users are choosing in dropdown some clauses. When they leave some box empty, I want query to ignore clause. I know CASE, and best I thought of is that if I pass 0 to parameter in stored procedure, it ignores that parameter, like this.

WHERE a.Country = (CASE WHEN @Country > 0 THEN @Country ELSE (something else) END)

so, (something else) should be like no condition, it can be '>0' as country ids are from all >1, but I don't know how to use > and = in same CASE.

Any suggestions?

This question is related to sql sql-server case where

The answer is


(something else) should be a.Country

if Country is nullable then make(something else) be a.Country OR a.Country is NULL


.. ELSE a.Country ...

I suppose


Try this:

WHERE a.Country = (CASE WHEN @Country > 0 THEN @Country ELSE a.Country END)

You can simplify to:

WHERE a.Country = COALESCE(NULLIF(@Country,0), a.Country);

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to case

PostgreSQL CASE ... END with multiple conditions SQL Server: use CASE with LIKE SQL Server IIF vs CASE SELECT using 'CASE' in SQL SELECT query with CASE condition and SUM() GROUP BY + CASE statement SQL use CASE statement in WHERE IN clause SQL Server - Case Statement where to place CASE WHEN column IS NULL in this query Regarding Java switch statements - using return and omitting breaks in each case

Examples related to where

Get only records created today in laravel Can I do Model->where('id', ARRAY) multiple where conditions? SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel SQL Query with Join, Count and Where PHP MySQL Query Where x = $variable How to use NULL or empty string in SQL Rails: Using greater than/less than with a where statement CASE in WHERE, SQL Server How to use "like" and "not like" in SQL MSAccess for the same field? Can the "IN" operator use LIKE-wildcards (%) in Oracle?