views:

35

answers:

2

In my database I have a table in which one of the columns is storing joining_months in string format like January, February, March....(and so on).

Now I want to run a SQL query on this table to fetch those rows only in which joining month is before or after a user specified month.

Something like:

select * from table1 where joining_month >or< 'March'

How can I compare the months stored in string format like this?

Please help !

+3  A: 

You should have another column on the table which has the numeric value of the month associated with the name, e.g. 1 for "January", 2 for "February", etc.

Then, you can simply filter on the name of the string while doing the comparison on the numeric value.

Just be cautious, a direct comparison like this only works if the months are in dates that are for the same year. If they are in different years, then comparing the months is pointless unless you take the year into account.

casperOne
For me its not possible to make any changes in database.And I don't have to care about years coz the application maintains data of a single year.
Akshay
+3  A: 

I found this rather out-of-the-box way of doing this on this page:

Another way to do this would be: SELECT CHARINDEX(monthname,'XXJANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC')/3 AS monthNumber

You can modify it by first extracting the first 3 characters of the month from your table and comparing that to the hard-coded string 'XXJANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'. That should do it.

So your query can be something like this:

   select CHARINDEX(substing(joining_month,1,3),'XXJANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC')/3
            AS monthnumber, * 
            from table1 
            where monthnumber >or< 3
Raze2dust
You would not need the /3 if month number is not needed. Quite clever if you can't change schema
gbn
+1 for cleverness
quantumSoup
really good method.. working successfully.. thanks a lot..!
Akshay