Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have select query which i need to order by ascending order. Column has varchar datatype so i need to convert it to int. My query is working fine but there is some situation when the user needs to enter such values '121-1' so it gives an error on select query 'Conversion failed when converting the varchar value '121-2' to data type int.' So is there any solution to ignore this error even on entering such values('121-1'). ? Following is my query
SQL
select ([Casetype] +'/'+ convert(varchar(50),CaseNo) +'/'+ convert(varchar(50),YEAR(GETDATE())) )as CaseNo ,
    CaseNo_ID,
    convert(varchar(20),[fileDate],103) as DateOfFilling,
    DisrtictFrom,
    tbl_RecordRequisition.CompName,
    tbl_RecordRequisition.RespName,
    CaseStage,
    convert(varchar(20),NextDate,103) as NextDate,
    tbl_RecordRequisition.Remarks
from tbl_RecordRequisition
order by left(CaseNo_ID,2) asc ,
    right(CaseNo_ID,4) asc,
    CAST((replace(replace(CaseNo_ID,left(CaseNo_ID,3),''),right(CaseNo_ID,5),'')) as int) asc

please help
Posted
Updated 26-Aug-15 21:39pm
v2
Comments
Maciej Los 27-Aug-15 3:36am    
Please provide input data and expected output. It might help us to understand your issue.
Maciej Los 27-Aug-15 3:41am    
Crosspost: http://stackoverflow.com/questions/32242994/error-in-order-by-in-sql-server

"So is there any solution to ignore this error even on entering such values('121-1')."
No.

That is expected behaviour - if you want to use integers, then use integer columns, or in your case probably two columns to establish a range.
You could use SUBSTRING to break out each number independently, but storing them properly is a lot less work in the long run!
 
Share this answer
 
Comments
Arasappan 27-Aug-15 3:41am    
nice
Two answers[^] to your question have been posted on SO. Use it!
 
Share this answer
 
Following query helped me

SQL
order by left(CaseNo_ID,2) asc ,right(CaseNo_ID,4) asc, (select CAST((tbl_RecordRequisition.CaseNo) as int)  where tbl_RecordRequisition.CaseNo not like '%-%' ) asc


Thanks all
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900