July 7, 2009 at 2:16 pm
I am grabbing data from an INFORMIX database and putting a constraint on a field that is data type CHAR. The field represents a date of MMYY (0709). I just found out it was a character field.
example: select * from table where field >= '0709'
I would like to get all data that is greater than 0709 but because it is a data type CHAR I get all data of previous years also like 0799.
What can I do to get only the data after 0709 from a character field.
Thanks
July 7, 2009 at 2:43 pm
What you'd want to do is extract out the month and date using substring. Then you can cast this as a number, and sort appropriately.
So
Where cast( substring( field, 1, 2) as int) > 7 -- to get things after July
and cast( substring( field, 3, 2) as int) > 9 -- get years greater than 09
and cast( substring( field, 3, 2) as int) < 80 -- set some limit to handle the 2 digit year.
You'd have to play with the specifics you want, and it will be hard to figure this out with a 2 digit year. SQL Server has a setting to decide when a year is the 20th century and when the 21st for this very reason.
July 19, 2009 at 11:23 pm
Provided that you will always have a 2 digit month and a 2 digit year, all you have to do is flip the MMYY to YYMM, add the DD part and do a normal date comparison. You might want to add a calculated column to the table to produce such dates so you don't need to constantly figure this out...
DECLARE @Date CHAR(4)
SELECT @Date = '0709'
SELECT CAST(RIGHT(@Date,2)+LEFT(@Date,2)+'01' AS DATETIME)
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply