开发者

SELECT min date for a varchar column

开发者 https://www.devze.com 2023-03-23 19:32 出处:网络
The date column of my table is VARCHAR not datetime. Eg entr开发者_Go百科y \'03/01/2011\' \'03/22/2011\'

The date column of my table is VARCHAR not datetime.

Eg

entr开发者_Go百科y
'03/01/2011'
'03/22/2011'
'05/22/2010'

when I do a

SELECT min(entry) FROM table

I will get '03/01/2011' as it is the min in alphabetical order. I want to retrieve '05/22/2010' instead which is the min date. How do I convert the column to datetime and get the min.

Thanks


Assuming all entries are 'castable' as datetime:

SELECT MIN(CAST(entry as datetime))
FROM table

Assuming there might be some cases where entry isnt a datetime:

SELECT MIN(CAST(ISNULL(NULLIF(ISDATE([entry]),0),'31/12/9999') as datetime))
FROM table

If all records are a date column, as @Steve Wellens recommended, I would change the datetype to a datetime field to save future problems


I would fix your database schema. Change the column type to a datetime. Otherwise you'll have problems forever.


Make your varchar a date (or datetime) by using CAST or CONVERT of course.


Try CASTing it.

SELECT min(CAST(entry AS DATETIME)) FROM table

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消