Quantcast
Viewing all articles
Browse latest Browse all 265

If parameter is null then select all data in SQL Server Query

We have a scenario, suppose we have a table like below


CREATETABLEEMP
(
       FNAMEVARCHAR(100)
       ,LNAMEVARCHAR(100)
       ,CREATEDDATEDATETIME,
)

INSERTINTOEMP
SELECT'DILIP','SINGH',GETDATE()
UNIONALL
SELECT'ANIL','SINGH',GETDATE()
UNIONALL
SELECT'ASHISH','PRATAP',GETDATE()


See following SQL statements


DECLARE@myNameVARCHAR(20)='ANIL'
SELECTFNAMELNAMEFROMEMP
WHEREFNAME= @myName



Here @myName parameter is declared and condition are if @myName =Null then return all records otherwise return related records.

Please see following query which can resolve this problem


DECLARE@myNameVARCHAR(20)=NUll
SELECTFNAMELNAMEFROMEMP
WHEREFNAME=ISNULL(@myName,FNAME)


We can use ISNULL function which checked if parameter @myName is Null then return FNAME column.Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 265

Trending Articles