min and max function tsql

/*
=============================================
Author: Bas van den Berg
Create date: 2014-02-25
Description: returns the minimum of two numbers
============================================
select dbo.udf_max(1,2)
select dbo.udf_max(null,2)
select dbo.udf_max(2,null)
select dbo.udf_max(2,3)
*/
ALTER FUNCTION [dbo].[udf_max]
(
@a sql_variant,
@b sql_variant

)
RETURNS sql_variant
AS
BEGIN
if @a is null or @b > @a
return @b
else
if @b is null or @a > @b
return @a
return null
END

/*
=============================================
uthor: Bas van den Berg
Create date: 2014-02-25
Description: returns the minimum of two numbers
============================================
select dbo.min(1,2)
select dbo.min(null,2)
select dbo.min(2,null)
select dbo.min(2,3)
*/
ALTER FUNCTION [dbo].[udf_min]
(
@a sql_variant,
@b sql_variant

)
RETURNS sql_variant
AS
BEGIN
if @a is null or @b < @a
return @b
else
if @b is null or @a < @b
return @a
return null
END

 

Leave a Reply

Your email address will not be published. Required fields are marked *