SQL:使用此函数获取最多四个日期之间的最小日期,如果要查找两列的最小值,只需为 date3 和 date4 传递 null。
--Use this function to get least date
--SELECT dbo.GetLeastDate('2021-01-19 01:09:28.997', '2021-01-19 01:07:28.997', '2021-01-19 00:02:28.997', '2021-01-19 02:05:28.997') as theDate
--SELECT dbo.GetLeastDate('2021-01-19 01:09:28.997', '2021-01-19 01:07:28.997', '2021-01-19 02:05:28.997', null) as theDate
--SELECT dbo.GetLeastDate('2021-01-19 01:09:28.997', '2021-01-19 01:07:28.997', null, null) as theDate
--SELECT dbo.GetLeastDate('2021-01-19 01:09:28.997', null, null, null) as theDate
CREATE OR ALTER FUNCTION [dbo].[GetLeastDate]
(
@d1 datetime,
@d2 datetime,
@d3 datetime,
@d4 datetime
)
RETURNS datetime
AS
BEGIN
DECLARE @least datetime
IF @d1 is null
and @d2 is null
and @d3 is null
RETURN null
Set @d1 = Isnull(@d1, getDate())
Set @d2 = Isnull(@d2, getDate())
Set @d3 = Isnull(@d3, getDate())
Set @d4 = Isnull(@d4, getDate())
IF @d1 < @d2 and @d1 < @d3 and @d1 < @d4
SET @least = @d1
ELSE IF @d2 < @d1 and @d2 < @d3 and @d2 < @d4
SET @least = @d2
ELSE IF @d3 < @d1 and @d3 < @d2 and @d3 < @d4
SET @least = @d3
ELSE
SET @least = @d4
RETURN @least
END