Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL equivalent of Excel "MAX" function to return larger of two numbers [duplicate]

Possible Duplicate:
Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

In Excel, there's a function called "MAX" that accepts numbers and returns the largest one in the set. Is there a function in T-SQL that duplicates this functionality? I haven't been able to find one, and I've written a UDF that does it for me, but I thought it was worth asking.

Here is the function I've been using:

CREATE FUNCTION dbo.LargerOf
(
    -- Add the parameters for the function here
    @First FLOAT,
    @Second FLOAT
)
RETURNS FLOAT
AS
BEGIN

    DECLARE @Result FLOAT

    IF @First > @Second
        SET @result = @First
    ELSE
        SET @Result = @Second

    RETURN @Result

END
GO

I don't expect any luck, but instead of moving my function to a whole bunch of new servers, I thought I'd at least ask. Thanks!

like image 970
SqlRyan Avatar asked Jun 12 '09 22:06

SqlRyan


4 Answers

I don't know if the function you need exists, but for a workaround, I like this one better

set @max = case when @first > @second then @first else @second end
like image 98
tekBlues Avatar answered Sep 28 '22 09:09

tekBlues


You could use:

CASE
   WHEN @First >= @Second THEN @FIRST
   ELSE @Second
END
like image 42
Tor Haugen Avatar answered Sep 28 '22 09:09

Tor Haugen


declare @first int, @second int

select @first=45, @second=123

select max(a) from (select @first a UNION ALL select @second) x

--OR

select max(a) from (values (@first),(@second)) x(a)

like image 41
msi77 Avatar answered Sep 28 '22 09:09

msi77


Unfortunately not.

A word of warning, for extremely intensive usage, I've found that scalar functions (even those which could be easily inlined with a CASE, like yours) really do not perform well on SQL Server 2005, so if you are dealing with millions of calls, put it inline (sometimes you can fake an inline TVF).

Hopefully, SQL Server will eventually have an inline SVF or have a function equivalent to GREATEST!

like image 29
Cade Roux Avatar answered Sep 28 '22 09:09

Cade Roux