Return zero if value less than zero [duplicate]

2019-03-06 06:08发布

问题:

This question already has an answer here:

  • Is there a Max function in SQL Server that takes two values like Math.Max in .NET? 28 answers

Is it possible to return zero if a value is less than zero without using a case statement?

e.g. Max(a, 0) <-- 'Max' doesn't exist.

I would like my code to be as succinct as possible.

回答1:

Just for fun:

DECLARE @a INT = -3
SELECT COALESCE(NULLIF (ABS(@a), -@a), 0)

This post just hints in the direction that a CASE expression is a much better option to get the expected result.

NULLIF is, after all, just a fancy CASE. The example query above expands (in the execution plan) to:

CASE 
    WHEN 
        CASE 
            WHEN abs([@a])=( -[@a]) 
            THEN NULL 
            ELSE abs([@a]) 
        END IS NOT NULL 
    THEN 
        CASE 
            WHEN abs([@a])=( -[@a]) 
            THEN NULL 
            ELSE abs([@a]) 
        END 
    ELSE (0) 
END

A suitable CASE expression:

-- All versions
SELECT CASE WHEN @a > 0 THEN @a ELSE 0 END;

-- SQL Server 2012 or later
SELECT IIF(@a > 0, @a, 0);