Вопрос

I've studied all similar questions here, none of them works, what can be the problem? I want to convert varchar to date

convert(date,substring(replace(ent.Value,' ',''),1,10),103) < '20140101' 

It returns error Conversion failed when converting date and/or time from character string.

ent.Value here is something like '28/02/2014' Actually it works, when I enter something like

convert(date,substring('28/02/2013',1,10),103) < '20140101'

, but it doesn't work directly from the table

Thanks

Это было полезно?

Решение

To convert varchar to datetime : CONVERT(Datetime, '28/02/2014', 103) return the datetime like February, 28 2014 00:00:00+0000

To convert datetime to varchar : CONVERT(VARCHAR(10), datetime_field, 103) return something like '28/02/2014'

In both case you cannot compare it to this kind of text : '20140101'

You can change your text so both informations are ISO like : CONVERT(VARCHAR(10), CONVERT(Datetime, ent.Value, 103), 103) < '01/01/2014'

Or REPLACE(ent.Value,'/','') < '01012014'

But I don't think it's good to compare varchar => you can also do something like this : CONVERT(Datetime, '20140101', 112) :

CONVERT(Datetime, ent.Value, 103) < CONVERT(Datetime, '20140101', 112)

So your both field are in Datetime. ex : SQLFIDDLE DEMO

Другие советы

Break it down a bit: The first conversion works fine with the given example date string, but then you try and compare a DATE to a VARCHAR which requires an implicit conversion. That's never a good sign. However that actually works, so that aside the chances are that you have a date stored in text format that isn't a valid date. Since your examples use the UK date format, perhaps you have an American date in there (02/28/2013 - mm/dd/yyyy). If your default date format is UK style (i.e. you're not using American English settings) then it will fail as being out of range. You might also have entries which aren't dates at all with text in them like wibble or badly formatted dates like 02 Fub 2013.

Basically, you have a duff date somewhere in your table which you'll need to track down. Dates stored as text are a curse and to be avoided at all costs (although I appreciate that's not always possible when you inherit a legacy system - been there myself).

EDIT

To find your possible bad dates try this:

SELECT * FROM MyTable WHERE ISDATE(MyDateAsTextCol) <> 1
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top