3

I have three values and I have to find MAX value from these values

Example:

DECLARE @r int=10
DECLARE @s int=15
DECLARE @t int=50

SELECT MAX(@r, @s, @t) 

I have to find 50 like this

1
  • A temp table would solve it declare @tmpTable table (value integer), insert your values to temp table and select max(value) Jan 23, 2014 at 9:22

4 Answers 4

8
DECLARE @r int=10,  @s int=15, @t int=50

SELECT max(val)
  from (values(@r),(@s),(@t)) X(val)
6

You should be using a code like this:

DECLARE @temp TABLE (a INTEGER)
INSERT INTO @temp VALUES(1)
INSERT INTO @temp VALUES(2)
INSERT INTO @temp VALUES(3)

SELECT MAX(a) FROM @temp

You can't run MAX on more variables. MAX() takes only 1 parameter, the column name in a table.

But, if you have to use the variables, then:

DECLARE @temp TABLE(col1 INTEGER)

DECLARE @r int=10
DECLARE @s int=15
DECLARE @t int=50

INSERT INTO @temp(col1) values(@r)
INSERT INTO @temp(col1) values(@s)
INSERT INTO @temp(col1) values(@t)

SELECT MAX(col1) FROM @temp
1
  • Don't forget that if you have found an answer that works best for you, then to mark that answer as the correct one. Jan 23, 2014 at 9:38
4

You should not waste resources with temporary table solutions.

Just make an union of all those variables.

sqlFiddle

DECLARE @r int=10

DECLARE @s int=15

DECLARE @t int=50

SELECT max(t.value)
  from (select @r as value
        union
        select @s as value
        union
        select @t as value) t
0
SELECT max(v)
    FROM (
       SELECT 1 as v UNION
       SELECT 2 as v UNION
       SELECT 3 as v
     ) t

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.