在SQL Server上,如何从几个变量中找到MAX或MIN值

时间:2022-08-24 00:09:44

I just found out that the MAX() function in SQL only works on columns.

我刚刚发现SQL中的MAX()函数只适用于列。

Is there a similar function I can use to find the max value out of e.g. these four variables?

是否有类似的功能我可以用来找到例如最大值这四个变量?

SET @return = MAX(@alpha1, @alpha2, @alpha3, @alpha4)

Or do I have to put them in a column first (and thus create a table first...;-( )?

或者我必须先将它们放在一列中(然后首先创建一个表...... ;-()?

Regards

Lumpi

1 个解决方案

#1


10  

There is no built-in function in T-SQL for this but you can use following

T-SQL中没有内置函数,但您可以使用以下内容

SELECT @result = MAX(alpha)
FROM   (SELECT @alpha1
        UNION ALL
        SELECT @alpha2
        UNION ALL
        SELECT @alpha3) T(alpha);  

or (SQL Server 2008+)

或(SQL Server 2008+)

SELECT @result = MAX(alpha)
FROM  (VALUES(@alpha1),
             (@alpha2),
             (@alpha3)) T(alpha);  

#1


10  

There is no built-in function in T-SQL for this but you can use following

T-SQL中没有内置函数,但您可以使用以下内容

SELECT @result = MAX(alpha)
FROM   (SELECT @alpha1
        UNION ALL
        SELECT @alpha2
        UNION ALL
        SELECT @alpha3) T(alpha);  

or (SQL Server 2008+)

或(SQL Server 2008+)

SELECT @result = MAX(alpha)
FROM  (VALUES(@alpha1),
             (@alpha2),
             (@alpha3)) T(alpha);