SQL在查询日期数据时如何限定查询的日期格式

我表A中有个start_date的字段,正确的日期数据应该为20120412这种格式的,可是现在这个字段中有各种错误格式的数据,我想只要正确的日期数据,查询条件如何限定为正确的日期格式

如select * from A where。。=。。 省略号这边怎么写
比如有些错误数据为02012040,或者30120407,20121320 ,20120431,如何避开这些错误数据

像楼上的回答可能会出现 一种情况,如30120407 也会被认为转成3012年4月7号,这样肯定是不合适的,建议你找个最小的年份,或者编造一个最小和最大的年份:现在是2013年2月22日为最大值,然后定义你表里实际的最小值2011年1月1日:

你的start_date为date类型的sql:
select * from A where start_date between

to_date('20110101','yyyymmdd') and to_date('20130222','yyyymmdd');追问

日期前三位开头是201 的 那我的语句是
select * from A where
to_char(to_date(date,'yyyymmdd'),'yyyymmdd')=to_char(datea,'yyyymmdd') and
left(start_date3) = '201'
这样是吧?

追答

如果是201的话,就是最小值为20100101,最大值是今天:
select * from A where start_date between to_date('20100101','yyyymmdd') and to_date('20130222','yyyymmdd');

追问

TO_DATE不是sql的函数把,sql怎么改啊

追答

你试试:
select * from A where start_date between cast('20100101' as datetime) and cast('20130222' as datetime);

追问

从char数据类型到datetime数据类型的转换导致datetime值出界

追答

试试这个函数:
select * from A where start_date between Convert(‘20100101’,Getdate(),112) and Convert(‘20130222’,Getdate(),112);

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-02-22
select * from A where
to_char(to_date(date,'yyyymmdd'),'yyyymmdd')=to_char(datea,'yyyymmdd');追问

日期前三位开头是201 的 那我的语句是
select * from A where
to_char(to_date(date,'yyyymmdd'),'yyyymmdd')=to_char(datea,'yyyymmdd') and
left(start_date3) = '201'

这样是吧?

第2个回答  2013-02-22
sqlserver:
where isdate(col)=1