views:

40

answers:

3

Can I do WHERE operations on a calculated date field?

I have a lookup field, which has been written badly in SQL and unfortunately I can't change it. But basically it stores dates as characters such as "July-2010" or "June-2009" (along with other non date data). I want to extract the dates first (which I did using a LIKE opertor) and then extract data based on a date range.

 SELECT 
     BusinessUnit,
     Lookup,
     ReleaseDate 
 FROM 
 (
     SELECT TOP 10  
       LookupColumn As Lookup,
       BU as BusinessUnit,
       CONVERT(DATETIME, REPLACE(LookupColumn,'-',' ')) as ReleaseDate  
     FROM 
       [dbo].[LookupTable]
     WHERE 
       LookupColumn LIKE N'%-2010'
 ) MyTable
 ORDER BY ReleaseDate
 WHERE ReleaseDate = '2010-02-01'

I'm having issues with WHERE operator. I would assume creating a subquery to encapsulate the calculated field would allow me to do operations with it such as WHERE but maybe I'm wrong. Bottom line is it possible to do operations on calculated fields?

UPDATE: indeed I had the order mixed up and furthermore the LIKE operator was also returning non-date values such as TBD-2010 which were messing me up.

+1  A: 

You'd probably have an easier time encapsulating this table in a view and then querying the view. This way, your view alone contains the logic to convert this bit of awfulness into a normal DATETIME column.

MusiGenesis
+1  A: 

What "issues" are you having?

In your example, you can't have a WHERE clause AFTER an ORDER BY clause...

Robin Day
+2  A: 

You have the ORDER BY and WHERE clauses round the wrong way. Try switching them round:

...
) MyTable
 WHERE ReleaseDate = '2010-02-01'
 ORDER BY ReleaseDate
AdaTheDev