0

In the following query:

SELECT 
  DU.MESSAGEINSERTDATE 
from [MYSMSREPORT].[DBO].[SIXDAYSHISTORY] 
where
  (CONVERT(NVARCHAR, CONVERT(DATETIME, MESSAGEINSERTDATE, 104), 112) 
  BETWEEN 
     CONVERT(NVARCHAR, CONVERT(DATETIME, 01/08/2008, 104), 112) 
  AND CONVERT(NVARCHAR,CONVERT(DATETIME,31/09/2012,104),112))

I have this error:

Arithmetic overflow error converting expression to data type datetime

What is the problem?

4
  • I edited your question to be more clear. Please review this edit. Commented Sep 26, 2012 at 10:02
  • 01/08/2008 is math, '01/08/2008' is a date Commented Sep 26, 2012 at 10:03
  • 1
    did you try single quotes around the dates? '01/08/2008' and '31/09/2012' Commented Sep 26, 2012 at 10:04
  • 1
    In general, when you have more information to add, you should edit your existing question, not open a new one. I've voted to close the other one Commented Sep 26, 2012 at 10:39

1 Answer 1

2

The 31st September isn't a date, so SQL cannot convert it to one.

As an aside you should hard code dates in a culture inspecific format (yyyyMMdd). 01/08/2012 may convert to 1st August on your Server, but run on another and it could be 8th January. 20120801 will convert to 1st August on all machines.

In addition Why are you converting dates to NVARCHAR? You are removing any benfit of indices you have, and also performing needless implicit and explicit conversions. Assuming MESSAGEINSERTDATE is a DATETIME Column you could just use

WHERE MESSAGEINSERTDATE BETWEEN '20120801' AND '20120930'

If you need to remove the time from MESSAGEINSERTDATE use

CAST(MESSAGEINSERTDATE AS DATE)
Sign up to request clarification or add additional context in comments.

3 Comments

Rather than removing the time (which again negates any index usage), better would be MESSAGEINSERTDATE >= '20120801' AND MESSAGEINSERTDATE < '20121001' (i.e. switch to a semi-open interval)
@Damien_The_Unbeliever - CAST( AS DATE) is sargable
Check the execution plan here. The index is used despite using CAST( AS DATE).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.