简体   繁体   English

选择varchar列的最小日期

[英]SELECT min date for a varchar column

The date column of my table is VARCHAR not datetime. 我的表的日期列是VARCHAR而不是datetime。

Eg 例如

entry
'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. 我会得到'03 / 01/2011',因为它是字母顺序的分钟。 I want to retrieve '05/22/2010' instead which is the min date. 我想要检索'05 / 22/2010'而不是最小日期。 How do I convert the column to datetime and get the min. 如何将列转换为datetime并获取最小值。

Thanks 谢谢

Assuming all entries are 'castable' as datetime : 假设所有条目都是'castable'作为datetime

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

Assuming there might be some cases where entry isnt a datetime : 假设某些情况下entry不是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 如果所有记录都是日期列,正如@Steve Wellens建议的那样,我会将datetype更改为datetime字段以节省未来的问题

I would fix your database schema. 我会修复你的数据库架构。 Change the column type to a datetime. 将列类型更改为日期时间。 Otherwise you'll have problems forever. 否则你将永远有问题。

当然,使用CASTCONVERT使varchar成为date (或datetime )。

Try CAST ing it. 尝试CAST荷兰国际集团它。

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM