Wednesday, March 15, 2017

IsNull or Empty in SQL Server

We can fetch a Null value column using ISNULL() function.
If the value is empty then we'll use IsNull or Empty function...

We can use it two types:-

The simple code is : SELECT ISNULL(NULLIF(@parameter1, ''), @parameter2)

And the another way is to create a function :

/****** Function ::: IsNullOrEmpty Function ******/

IF EXISTS(SELECT * FROM SysObjects WHERE NAME = 'IsNullOrEmpty' AND XTYPE = 'FN')
BEGIN
       DROP FUNCTION IsNullOrEmpty
END
GO
       CREATE FUNCTION [dbo].[IsNullOrEmpty]
              (@value NVARCHAR(max),
               @return NVARCHAR(max)
              )
       RETURNS NVARCHAR(MAX)
       AS
       BEGIN

       IF (@value IS NULL)
       BEGIN
              RETURN @return
       END
       ELSE
       BEGIN
              IF (LEN(LTRIM(@value)) = 0)
              BEGIN
                     RETURN @return
              END
       END

       RETURN @value;
       END

       GO
Then we use this simple code : SELECT dbo.IsNullOrEmpty(@parameter1,@parameter2)

If there is any other better option,
Please share it here or mail to me arkaa4@gmail.com

Thank You,
Arka Gupta.


No comments:

Post a Comment