We help IT Professionals succeed at work.

Return latest of 2 dates

vtechdev
vtechdev asked
on
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.
Comment
Watch Question

AneeshDatabase Consultant
CERTIFIED EXPERT
Top Expert 2009

Commented:
SELECT MAX(urDateColumn) from urTable

Author

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.
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.
Database Consultant
CERTIFIED EXPERT
Top Expert 2009
Commented:
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

Author

Commented:
Thanks, I'm tired and the simplest and best solution was escaping me, thanks for providing it quickly.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.