0

I am facing issue while querying for some data from SQL. The column datatype is varchar which has datetime stamp as part of its name, like DUMMY2_20140713.pdf.

Want to search for files between week date duration.so trying to convert part of file name to date as below:

select file_name,file_name 
from t_pdf_weekly_violation 
where CONVERT(datetime, SUBSTRING(file_name, CHARINDEX('_', file_name) + 1, 8), 112) between 20150506 and 20150513;

But it is throwing exception..Please find stack trace below:

com.microsoft.sqlserver.jdbc.SQLServerException: Arithmetic overflow error converting expression to data type datetime. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196) at com.microsoft.sqlserver.jdbc.SQLServerResultSet$FetchBuffer.nextRow(SQLServerResultSet.java:4700) at com.microsoft.sqlserver.jdbc.SQLServerResultSet.fetchBufferNext(SQLServerResultSet.java:1683) at com.microsoft.sqlserver.jdbc.SQLServerResultSet.next(SQLServerResultSet.java:956) at databaseconnection.ConnectionURL.main(ConnectionURL.java:36)

Have any one idea on this?

Thanks in advance

5
  • just note, why two times file_name in select list in query Commented May 13, 2015 at 17:47
  • CONVERT(datetime replace with CONVERT(int Commented May 13, 2015 at 17:48
  • Piyush : taking substring of file name , so used file_name twice. Commented May 13, 2015 at 17:52
  • Lashane : I tried replacing datetime with int, still it is showing exception Commented May 13, 2015 at 17:52
  • @user3863488:- I not talking about sub-string, I mean to pointed out this code select file_name,file_name in your query Commented May 13, 2015 at 17:56

2 Answers 2

1

There is no need to convert substring to Datetime, just remove CONVERT(datetime

SELECT file_name,file_name 
FROM t_pdf_weekly_violation 
WHERE SUBSTRING(file_name, CHARINDEX('_', file_name) + 1, 8) between 20150506 and 20150513;

Sample SQL FIDDLE

Alternate Solution

If you want to use CONVERT(datetime, then you have to convert your all dates

SELECT file_name,file_name 
    FROM t_pdf_weekly_violation 
    WHERE CONVERT(datetime,SUBSTRING(file_name, CHARINDEX('_', file_name) + 1, 8),112) 
         between CONVERT(datetime,'20150506',112) and CONVERT(datetime,'20150510',112);

Sample SQL FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

0

It is working when I changed return type datetime to char, like

SELECT file_name,file_name 
    FROM t_pdf_weekly_violation 
    WHERE CONVERT(char(8),SUBSTRING(file_name, CHARINDEX('_', file_name) + 1, 8),112) 
         between CONVERT(char(8),'20150506',112) and CONVERT(char(8),'20150510',112);

Comments

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.