SQL Server Return All Records If Search Text is Blank

Sometimes, depending on business requirements, we need to fetch all records if the search text parameter is blank. We have many ways to satisfy that requirement.

I have the following Employee Table in my SQL Server:

  1. SELECT * FROM EMPLOYEE  


CASE 1

Now if we pass a Search Parameter to select records from this table.
  1. DECLARE @SEARCHTEXT VARCHAR(50)  
  2. SET @SEARCHTEXT='Ra'  
  1. SELECT * FROM EMPLOYEE WHERE NAME LIKE '%'ISNULL(@SEARCHTEXT, NAME) +'%'  


Now set SearchText to null or blank.
  1. DECLARE @SEARCHTEXT VARCHAR(50)  
  2. SET @SEARCHTEXT=''  
  1. SELECT * FROM EMPLOYEE WHERE NAME LIKE '%'ISNULL(@SEARCHTEXT, NAME) +'%'  


Case 2

  1. DECLARE @SEARCHTEXT VARCHAR(50)  
  2. SET @SEARCHTEXT=''  
  1. IF(LEN(@SEARCHTEXT)>0)  
  2. SELECT * FROM EMPLOYEE WHERE NAME=@SEARCHTEXT  
  3. ELSE  
  4. SELECT * FROM EMPLOYEE WHERE NAMENAME  

 

Up Next
    Ebook Download
    View all
    Learn
    View all