views:

98

answers:

3
table1
    - date1 datetime not null
    - date2 nvarchar null

I want to get the latest date of this two.

select date1, date2, 
(CASE WHEN date1 > CAST(date2 as DateTime) THEN date1 ELSE date2 END) as DateTime) as LatestDate
from table1

please note that date2 can be null. in this case, date1 win.

+1  A: 
SELECT date1, date2,  
CASE 
  WHEN date1 > CAST(ISNULL(date2,'1900-01-01') as DateTime) THEN 
     date1 
  ELSE 
    CAST(date2 as DateTime) 
END  as LatestDate 
FROM table1
Nathan Fisher
oups .. +1 did not see your answer until after i had posted the same..
Gaby
@Nathan Thank you!
stacker
How can I use it in update query? the update will be put the grate value in a new column.
stacker
@stacker `update table1 set newcolumn = CASE .... END`
Gaby
+1 for @Gaby answer about the update
Nathan Fisher
+1  A: 

change CAST(date2 as DateTime) to CAST(isnull(date2,'01/01/1900') as DateTime)

Gaby
A: 

This is very nice solution, but I suspect Nathan's solution is better.

http://p2p.wrox.com/oracle/6592-calculate-de-max-value-two-columns.html

stacker