开发者

check if a value is NULL or Less than 0 in one TSQL statement

ISNULL(SUM(MyTable.Total), 0) AS Total

How can I modify the above statement to also check if Total 开发者_Python百科is less than 0 (zero), such that If Total is NULL or less than 0 (negative), I assign 0 to Total


CASE WHEN ISNULL(SUM(MyTable.Total), 0) <= 0 THEN 0
     ELSE SUM(MyTable.Total)
END AS Total


CASE 
WHEN COALESCE(SUM(MyTable.Total), 0) <= 0 THEN 0
ELSE SUM(MyTable.Total)
END AS [Total]


Just to be different...

ISNULL(SUM(Total) * NULLIF(SIGN(SUM(Total)), -1), 0)


CASE WHEN 
  COALESCE(SUM(MyTable.Total),0) <= 0 
THEN 
   0 
ELSE 
  SUM(MyTable.Total)
END AS Total


@SQL.NET Warrior, I have created a function for you. It takes an integer as parameter and retuns 0 for NULL or negative values.

--this statements ensure we drop the function before recreating it
IF EXISTS(SELECT * FROM sysobjects WHERE xtype = 'FN' AND name = 'nonNullNegative')
BEGIN
    DROP FUNCTION dbo.nonNullNegative
END
GO

--the real function definition
CREATE FUNCTION dbo.nonNullNegative(@numValue INT)
RETURNS INT
AS
BEGIN
  DECLARE @newValue AS INT; 
    SET @newValue= CASE WHEN ISNULL(@numValue,0)<=0 THEN 0 ELSE @numValue
END
    RETURN  @newValue;
END
GO



use MyDatabase;

--use it like this
SELECT dbo.nonNullNegative(-2);--outputs 0


How about

SUM(ISNULL(MyTable.Total, 0)) AS Total

I prefer this as the NULL implementation in databases is not always logical and does differ between vendors and whether ANSI_NULLS are enabled or not.

E.g. SUM of NULL, NULL and 1 is returned as 1, but (1 + NULL + NULL) is equal to NULL ...

You can then do the less than 0 with the CASE as above, thus

CASE 
WHEN SUM(ISNULL(MyTable.Total,0)) <= 0 THEN 0
ELSE SUM(ISNULL(MyTable.Total,0))
END AS [Total]


In Postgresql since there is no IS NULL function you can do:

CASE WHEN SUM(MyTable.Total) > 0 THEN SUM(MyTable.Total) ELSE 0 END AS Total


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Haluk Alkın Turan
-- Create date: 2017-10-31
-- Description: Simulates ORACLE's GREATEST Function
-- Usage: select dbo.getGreatest(1,2)
-- =============================================
CREATE FUNCTION getGreatest
(
    @val1 sql_variant,
    @val2 sql_variant
)
RETURNS sql_variant
AS
BEGIN
    RETURN (SELECT MAX(i) FROM (VALUES (@val1), (@val2)) AS T(i))
END
GO


select greatest(0, -1) FROM DUMMY

It returns 0

select greatest(0, 1) FROM DUMMY

It returns 1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜