Thursday, March 31, 2016

Zero(0) value check in SQL Server

Here we discuss about Zero(0) value check in SQL Server. If any field value is 0 then we put another value instead of Zero(0).

So, first we can do it using a function. we create a function and use it. 

IF EXISTS(SELECT * FROM SysObjects WHERE NAME = 'ISZERO' AND XTYPE = 'FN')
      BEGIN
            DROP FUNCTION ISZERO
      END
GO
      CREATE FUNCTION [dbo].[ISZERO] (@Number FLOAT,
                                      @IsZeroNumber FLOAT)
      RETURNS FLOAT
      AS
      BEGIN
            IF (@Number = 0)
            BEGIN
                  SET @Number = @IsZeroNumber
            END
            RETURN (@Number)
      END
GO
      DECLARE @ZERO AS FLOAT = 0
      DECLARE @NUMBER AS FLOAT = 3103.2016
GO
      SELECT [dbo].[ISZERO](@ZERO,@NUMBER)

RESULT: 3103.2016

And the another way we use ISNULL() and NULLIF().

DECLARE @ZERO AS FLOAT = 0
DECLARE @NUMBER AS FLOAT = 3103.2016
GO

SELECT ISNULL(NULLIF(@ZERO,0),@NUMBER)

RESULT: 3103.2016

No comments:

Post a Comment