CREATE FUNCTION [dbo].[DATETIME_GREATEST_3PARAM]
(@val1 DATETIME, @val2 DATETIME,@val3 DATETIME)
returns DATETIME
AS
BEGIN
    Declare @result DATETIME
    set @result = case when @val1 > @val2 then
               case when @val1 > @val3 then
                @val1
               else
                @val3
               end
        when @val2 > @val3 then
                @val2
        else
                 @val3
    end
    return @result
END