从声明的值(变量)中查找MAX值

Mür*_*zlü 2 t-sql sql-server

我有三个值,我必须MAX从这些值中找到值

例:

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

SELECT MAX(@r, @s, @t) 
Run Code Online (Sandbox Code Playgroud)

我必须找到50这样的

小智 6

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

SELECT max(val)
  from (values(@r),(@s),(@t)) X(val)
Run Code Online (Sandbox Code Playgroud)


Rad*_*hiu 5

你应该使用这样的代码:

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
Run Code Online (Sandbox Code Playgroud)

您无法运行MAX更多变量.MAX()只接受一个参数,即表中的列名.

但是,如果你必须使用变量,那么:

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
Run Code Online (Sandbox Code Playgroud)