On SQL Server, how to find the value of MAX or MIN from a pair of variables

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

Is there a similar function that I can use to find the maximum value from, for example, these four variables?

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

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

Hi

Lumpi

+6
source share
1 answer

There is no built-in function in T-SQL, but you can use the following

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

or (SQL Server 2008 +)

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

Source: https://habr.com/ru/post/899201/


All Articles