• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 607
  • Last Modified:

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.
0
vtechdev
Asked:
vtechdev
  • 2
  • 2
1 Solution
 
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
 
vtechdevAuthor Commented:
Thanks, I'm tired and the simplest and best solution was escaping me, thanks for providing it quickly.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now