Return latest of 2 dates

What is the best way to compare 2 dates and return the larger date when it cannot be known in advace if both or even either date will exist.
If no dates exist I expect a null, if only 1 date exists I expect that date, but if both exist I expect the later date.
vtechdevAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Aneesh RetnakaranDatabase AdministratorCommented:
SELECT MAX(urDateColumn) from urTable
0
vtechdevAuthor Commented:
Let me clarify, I really want to write a User Defined Function(UDF) to return the later of 2 dates, but the UDF must allow 1 or both of the dates to be null and still function. I don't want the MAX from a table.
0
adamsetzlerCommented:
Or, if you want to manipulate the data later:

SELECT yourIdField, MAX(yourDateColumn) as yourMaxDate FROM yourTable GROUP BY yourIdField

This will return a list of unique IDs, each one being the most recent date.  Conversely, you could use MIN() to select the oldest.
0
Aneesh RetnakaranDatabase AdministratorCommented:
CREATE FUNCTION dbo.retMaxDate (
@Date1 DATETIME = NULL,
@Date2 DATETIME = NULL )
RETURNS DATETIME
AS
BEGIN
      IF @Date1 > @Date2 OR @Date2 IS NULL
            RETURN (@Date1)
      RETURN (@Date2)
END

GO
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
vtechdevAuthor Commented:
Thanks, I'm tired and the simplest and best solution was escaping me, thanks for providing it quickly.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.