Search:
Welcome Guest | Register | Login
logo

Select all records if parameter is null or empty

How to select all records from table if parameter is null or empty

OR

You can say apply parameter if it is not null or not empty.

CREATE PROC Customer_Fetch
     @Name   Varchar(50)     
    ,@City  Varchar(50)
AS
    SELECT * FROM Customers
    WHERE CustomerName = @Name
      AND City = @City    
  • SQL Server
1
 
Asked: 02 Mar 2013
Reputation: 15
Nicholas Marijan
2 Answers

Try this for Null

WHERE (CustomerName = @Name OR @Name IS NULL)
      AND (City = @City OR @City IS NULL)

Try this for Empty

 WHERE (CustomerName = @Name OR @Name = '')
      AND (City = @City OR @City  = '')      
1
 
Answered: 02 Mar 2013
Reputation: 52
Nikita Bhavsar

You can use ISNULL and match with the same column values

WHERE CustomerName = ISNULL(@Name, CustomerName)
      AND City = ISNULL(@City, City)
0
 
Answered: 02 Mar 2013
Reputation: 1,109
Myghty
Login to post your answer