Click here to Skip to main content
15,886,861 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
0 down vote favorite


I have sql order by asc query and i have to order varchar field which contains integer value(I can't change the data type to int as there is already lots of data in that table changing may lose data). Result of the sorting is as following
1 2 3 . . 8 9 10 101 102 103 . . 109 11 110 111 . . 119 12

Result should be 1 2 3 . . 8 9 10 11 12

query is
C#
dbAccess.execute("SELECT [id],[SNo],LetterSNO,[SubjectOfLetter],[FrmWhere],[WhomTosend],(Cast(Day(DateOfRecieve) as Varchar(3))+'/'+Cast(Month(DateOfRecieve) as Varchar(2))+'/'+Cast(Year(DateOfRecieve) as Varchar(4))) as DateOfRecieve ,[Remarks] ,[User_IPAddress], (Cast(Day(DateOfSending) as Varchar(3))+'/'+Cast(Month(DateOfSending) as Varchar(2))+'/'+Cast(Year(DateOfSending) as Varchar(4))) as DateOfSending FROM [MpscdrcTESTING].[dbo].[tbl_PostalEntry] where DateOfRecieve between '" + TextBox1.Text.Trim() + "' and  '" + TextBox2.Text.Trim() + "' order by SNo asc";


please help
Posted

use cast function and change the query by below.

dbAccess.execute("SELECT [id],CAST([SNo] as int) as SNumber,LetterSNO,[SubjectOfLetter],[FrmWhere],[WhomTosend],(Cast(Day(DateOfRecieve) as Varchar(3))+'/'+Cast(Month(DateOfRecieve) as Varchar(2))+'/'+Cast(Year(DateOfRecieve) as Varchar(4))) as DateOfRecieve ,[Remarks] ,[User_IPAddress], (Cast(Day(DateOfSending) as Varchar(3))+'/'+Cast(Month(DateOfSending) as Varchar(2))+'/'+Cast(Year(DateOfSending) as Varchar(4))) as DateOfSending FROM [MpscdrcTESTING].[dbo].[tbl_PostalEntry] where DateOfRecieve between '" + TextBox1.Text.Trim() + "' and  '" + TextBox2.Text.Trim() + "' order by 2 asc";
 
Share this answer
 
Comments
ankitsrist 8-Jan-15 6:36am    
thanks praveen it works :)
Praveen Kumar Upadhyay 8-Jan-15 6:37am    
My pleasure.
C#
ORDER BY CAST(sNO as INT)


this will work
 
Share this answer
 
See this

http://stackoverflow.com/questions/16829663/sql-server-query-varchar-data-sort-like-int[^]



dbAccess.execute("SELECT [id],[SNo],LetterSNO,[SubjectOfLetter],[FrmWhere],[WhomTosend],(Cast(Day(DateOfRecieve) as Varchar(3))+'/'+Cast(Month(DateOfRecieve) as Varchar(2))+'/'+Cast(Year(DateOfRecieve) as Varchar(4))) as DateOfRecieve ,[Remarks] ,[User_IPAddress], (Cast(Day(DateOfSending) as Varchar(3))+'/'+Cast(Month(DateOfSending) as Varchar(2))+'/'+Cast(Year(DateOfSending) as Varchar(4))) as DateOfSending FROM [MpscdrcTESTING].[dbo].[tbl_PostalEntry] where DateOfRecieve between '" + TextBox1.Text.Trim() + "' and '" + TextBox2.Text.Trim() + "' order by CAST([SNo] AS INT) asc";
 
Share this answer
 
v2

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