Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SERVER: Check if variable is null and then assign statement for Where Clause

I am trying to achieve something like the below in WHERE clause in sql.

if (@zipCode ==null)
begin
([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)   
end
else if(@zipCode !=null)
begin
([Portal].[dbo].[Address].PostalCode=@zipCode )
end  

I tried the following:

WHERE ((@zipCode IS NOT NULL AND ([Portal].[dbo].[Address].PostalCode=@zipCode)) OR (@zipCode IS NULL AND ([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)))

which is wrong. Can anyone help in framing the exact statement. Thanks!

like image 417
Krishh Avatar asked Apr 18 '13 14:04

Krishh


People also ask

How do I check if a variable is NULL in SQL Server?

The IS NULL condition is used in SQL to test for a NULL value. It returns TRUE if a NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

IS NULL check in where clause?

Generally, NULL data represents data does not exist or missing data or unknown data. IS NULL & IS NOT NULL in SQL is used with a WHERE clause in SELECT, UPDATE and DELETE statements/queries to validate whether column has some value or data does not exist for that column.


1 Answers

is null is the syntax I use for such things, when COALESCE is of no help.

Try:

if (@zipCode is null)
  begin
    ([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)   
  end
else 
  begin
    ([Portal].[dbo].[Address].PostalCode=@zipCode )
  end  
like image 99
marceljg Avatar answered Oct 05 '22 23:10

marceljg