Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 get the earliest date??

Author  Topic 

helixpoint
Constraint Violating Yak Guru

291 Posts

Posted - 2014-12-10 : 09:23:07
I have two dates. How do I get the one that is the lowest. One may be null. I don't want null unless they are both null

Dave
Helixpoint Web Development
http://www.helixpoint.com

helixpoint
Constraint Violating Yak Guru

291 Posts

Posted - 2014-12-10 : 09:30:21
Tried something like...
DECLARE @Handle date
SELECT @Handle = dbo.getTrkLeastDate('2014-12-09',NULL)
print @Handle

ALTER FUNCTION [dbo].[getTrkLeastDate] (@d1 date, @d2 date)
RETURNS datetime
AS
BEGIN
DECLARE @least date

IF @d1 is null and @d2 is null
SET @least = null
ELSE IF @d1 < @d2 or @d2 is not null
SET @least = @d1
ELSE
SET @least = @d2

RETURN @least
END

Dave
Helixpoint Web Development
http://www.helixpoint.com
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-12-10 : 10:36:26
Or a little simpler:

select min(d) from (values (date1), (date2)) v(d)
Go to Top of Page
   

- Advertisement -