My dbase has date formats in 6 digits with a int datatype (‘734503’ = 01/01/2012).
I have been able to successfully convert these to char with:
SELECT CONVERT(char(12),dateadd(dd,(date_paid - 639906),'1/1/1753'),101)
FROM vouchers
WHERE date_paid = '734503'
This gives me the output of 01/01/2012.
But if I search on the converted date in a query like this:
SELECT CONVERT(char(12),dateadd(dd,(date_paid - 639906),'1/1/1753'),101)
FROM vouchers
WHERE date_paid >= '09/01/2012' AND date_paid <= '09/30/2012'
Why doesn’t the conversion take place? Even if I use a CONVERT in the WHERE statement on the date_paid field, shouldn’t it work there?
I suppose my question is how do I search with the converted character date and not have to use the 6 digit date?
Your problem is that you are comparing an INT column with STRING values, and expecting it to resolve as if comparing dates…
Because of the differing datatypes there is an implicit CAST() in there. Effectively you’re doing…
What you really need to do is explicitly manipulate the strings in to integers.
This too involves implicit casts. DATEDIFF() only takes DATETIME datatypes so the strings are implicitly cast to DATETIMEs first.
EDIT:
Another option would be to CAST() the
date_paidfield into a DateTime, then base theWHEREcaluse on that. The down side here is…– The CAST() would have to be done on every row, then the WHERE clause applied
– This prevents any use of indexes and dramatically reduces performance
The answer above does all the manipulation on the constant values, so that the searched field can be processed in it’s native state; thus allowing use of indexes.