Click here to Skip to main content
16,019,043 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
VB
how i can sort below varchar values 
13028-2DEW1
13028-2DEW10
13028-2DEW2
13028-2DEW3
13028-2DFB1
13028-2DLW1
13028-2DLW10
13028-2DLW101
13028-2DLW2
13028-2DLW7

i need output like this

13028-2DEW1
13028-2DEW2
13028-2DEW3
13028-2DEW10
13028-2DFB1
13028-2DLW1
13028-2DLW2
13028-2DLW7
13028-2DLW10
13028-2DLW101
Posted

Basically you can't - the sort order for a string value is always determined on the difference between characters, not a "total numeric value".

But if you convert the "end bit" to a number....
SQL
SELECT * FROM MyTable
ORDER BY SUBSTRING(MyColumn, 1, 10), CAST(SUBSTRING(MyColumn, 11, 1000) AS INT)

But - you might be better off constructing this as a Computed Column[^] and storing the various parts separately - it would save a lot of hassle!
 
Share this answer
 
Comments
Maciej Los 2-May-14 5:06am    
+5!
Please, see my answer. I'm using LEFT and RIGHT function instead of SUBSTRING.
Have a look at sample:
SQL
DECLARE @tmp TABLE (code VARCHAR(30))

INSERT INTO @tmp (code)
VALUES('13028-2DEW1'),
('13028-2DEW10'),
('13028-2DEW2'),
('13028-2DEW3'),
('13028-2DFB1'),
('13028-2DLW1'),
('13028-2DLW10'),
('13028-2DLW101'),
('13028-2DLW2'),
('13028-2DLW7')


SELECT code, LEFT(code,10) as begpart, CONVERT(INT, RIGHT(code, LEN(code)-10)) AS endpart
FROM @tmp
ORDER BY LEFT(code,10), CONVERT(INT,RIGHT(code, LEN(code)-10))



Result:
13028-2DEW1	13028-2DEW	1
13028-2DEW2	13028-2DEW	2
13028-2DEW3	13028-2DEW	3
13028-2DEW10	13028-2DEW	10
13028-2DFB1	13028-2DFB	1
13028-2DLW1	13028-2DLW	1
13028-2DLW2	13028-2DLW	2
13028-2DLW7	13028-2DLW	7
13028-2DLW10	13028-2DLW	10
13028-2DLW101	13028-2DLW	101


If you remove begpart and endpart from select list, you'll see only code values.
 
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