I am using WebMatrix with SQL Server Compact, and just have a simple question. I have a line of code:
if(cndDateLastModified=="gteq"){stringCompiler+="'CAST(DateLastModified AS datetime)' >= 'CAST(" + DateLastModified + " AS datetime)' ";}////
By plotting the output on the screen the query specifically looks like:
SELECT * FROM POITable WHERE 'CAST(DateLastModified AS datetime)' >= 'CAST(09/25/2012 AS datetime)'
For some reason, it returns all rows before, on, and after the date specified.
I’m still a little green when it comes to querying, but by all researched accounts, this should work. Clearly it is doing something I don’t quite expect, which is understandable, considering.
Any ideas on how I can get this to work the way I want it? Is it still trying to compare strings or some other format?
Note: I did try this with CONVERT(datetime, DateLastModified) and CONVERT(datetime, DateLastModified, 1) for both conversions.
Another Note: It is stored in the database as a string.
Another Note: If I switch the condition (from >= to <=) it does the opposite and returns no rows, which I would kind of expect considering the first unexpected result set, but still don’t know why.
Any ideas?
Because with the single quotes you are comparing two strings. ‘CAST(….)’ vs. ‘CAST(…)’. You may as well have written WHERE ‘Ginger’ >= ‘Fred’ you would get the same results. 😀
What you should need is:
FROM POITable WHERE CAST(DateLastModified AS datetime) >= CAST(’09/25/2012′ AS datetime)
Use the single quotes around the literal date. ’09/25/2012′
However if you’re using SQL server, you can just use WHERE CAST(DateLastModified AS datetime) >= ‘2012-09-25’
Additionally, if the DateLastModified column of the table is already a date time, remove the cast. Cast is for converting strings to data types. My hunch is all you need is: