Use something like LEAST in T-SQL on a datetime field

datetime, sql, sql-server, t-sql

Solution

There is no such function in T-SQL. Try:

SELECT theDate = CASE WHEN date1 < date2 THEN date1 ELSE date2 END FROM ... ;

To handle NULLs you may want:

SELECT theDate = NULLIF(CASE WHEN date1 < date2 THEN date1 ELSE date2 END, '20301231')
FROM 
(
  SELECT 
    date1 = COALESCE(date1, '20301231'), 
    date2 = COALESCE(date2, '20301231')
  FROM ...
) AS x;

Also, you can't reference the alias `theDate` in the `WHERE` clause, it doesn't exist yet. You might want to say:

WHERE '20120924' IN (date1, date2);

Problem

Possible Duplicate: Getting the minimum of two values in sql Okay what I Have a table with two datetime fields and I want to select the rows where the oldest date is equal to some date variable. I saw the LEAST function used somewhere but I can't use this in T-SQL I need something like this ``` SELECT LEAST(date1, date2) as theDate FROM theTable WHERE theDate = '2012-09-24' ``` but that will work in T-SQL. Also date1 or date2 can sometimes be null so that may be important to know.

Original source

Related problems