MSSQL:两数中的最大值或最小值

在mssql中,如果想知道两个数中的最大值,你可能会想到执行以下语句:

select max(1729,1024)

但是你获取的是两行错误信息:

消息 174,级别 15,状态 1,第 1 行
max 函数要求有 1 个参数。

也就是说,在 MSSQL 数据库中最大最小的函数只能针对字段来操作,无法取两数中的最大或最小.为此,我写了以下函数,来达到最两值最大或最小的目的:

以下两个函数则可以取出两数中的最大值或最小值:

-- 取两数中的最大数
create function imax(@n1 int,@n2 int)
returns int
as
begin
    declare @n int
    if(@n1 is null or @n2 is null) set @n = null
    if(@n1>@n2) set @n = @n1 else set @n = @n2
    return @n
end


-- 取两数中的最小数
create function imin(@n1 int,@n2 int)
returns int
as
begin
    declare @n int
    if(@n1 is null or @n2 is null) set @n = null
    if(@n1<@n2) set @n = @n1 else set @n = @n2
    return @n
end
 

执行结果:
select max(1729,1024)
1729

select min(1729,1024)
1024

 

你可能感兴趣的:(sql,mssql)