I checked your profile and saw that you are in the UK. If your sql server is set to use the dateformat dmy then that explains your issue. Without using the 'T' instead of the space in the datetime string, Sql Server won't recognize it as ISO8601 format.
Try this:
select count(*)
from dbo.profile
where [created] between convert(datetime,'2014-11-01T00:00:00.000')
and convert(datetime,'2014-11-30T23:59:59.997');
Querying using dates and/or datetimes can be tricky, to make sure you are getting what you are looking for I recommend reading:
edit: to clarify the out of range value in your error message would be from interpreting the month as 30 and the day as 11.
Well, first off, you should fix your table and store date/time data using the right kind of column, and not breaking it up for reasons unknown. Whose decision was it to store a time as a CHAR(6)
? Can you think of a single good reason for that? Where do you store the date? Was that 1 PM today, last Tuesday, or October 2012 sometime? This really should be a single datetime column. Have the "designers" please read this and this.
But barring that (funny how every time you suggest a table change, they say they can't change the table):
DECLARE @x TABLE(y CHAR(6));
INSERT @x(y) VALUES('131329');
SELECT DATEADD(MINUTE,5,CONVERT(TIME(0),STUFF(STUFF(y,5,0,':'),3,0,':')))
FROM @x;
Result:
13:18:29
If you find that query ugly and tedious, good! There's a good reason: You're storing your data wrong.
And this won't be the last problem you have with this design, either. What is stopping someone from inserting 967286
or foobar
or <empty string>
in your CHAR(6)
column? If you need to work around that problem, you can use TRY_CONVERT()
in 2012 and up (please always specify version with a version-specific tag), or a CASE
expression in earlier versions.
DECLARE @x TABLE(y CHAR(6));
INSERT @x(y) VALUES('foobar');
-- 2012:
SELECT DATEADD(MINUTE,5,TRY_CONVERT(TIME(0), STUFF(STUFF(y,5,0,':'),3,0,':')))
FROM @x;
-- older:
SELECT DATEADD(MINUTE,5,CONVERT(TIME(0),
CASE WHEN ISDATE(STUFF(STUFF(y,5,0,':'),3,0,':'))=1 THEN
STUFF(STUFF(y,5,0,':'),3,0,':') END))
FROM @x;
Best Answer
This will help you figure out what value is causing your error. The example below shows a table with a NULL, a word, and a time stamp. You can see by running a case when statement that analyzes the value to essentially see if it's a date or could be a date and prints the value that is not a date. The CTE wrap up gives us a clean cut view into what specific values are not dates, so you can edit that value.
As Erik said, you can do a try_convert to get the update to take. The approach below will show you which value is not converting.