Click here to Skip to main content
15,884,298 members
Articles / Programming Languages / SQL
Tip/Trick

Sorting column that contains string with numeric value

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
18 Nov 2011CPOL 13.7K   1  
Sorting column that contains string with numeric value
You must have to concern data sorting when you work with wide range of data source. Well nothing to say more about shorting which is very important. Okay let’s consider the following scenario:
You have a table with few columns & you will sort the table based on a specific column that contains numeric value with string type value. A sample table is given below:

Table# tempTable

c1 c2

1 368 Mirpur
2 243 Gulshan
3 101 DOHS
. …………..
etc.,

So now, you have to sort the table base on c2, how can you do that? It’s very simple, to achieve this we will use PATINDEX() function. The following query will resolve the issue.

Example:

SQL
DECLARE @tempTable TABLE (id INT, String_WithN_umericValue VARCHAR(100))
INSERT INTO @tempTable VALUES (1,’7th’)
INSERT INTO @tempTable VALUES(2,’4th’)
INSERT INTO @tempTable VALUES(3,’9th’)
INSERT INTO @tempTable VALUES(4,’10th’)
INSERT INTO @tempTable VALUES(5,’2nd’)
INSERT INTO @tempTable VALUES(6,’5th’)
INSERT INTO @tempTable VALUES(7,’8th’)
INSERT INTO @tempTable VALUES(8,’1st’)
INSERT INTO @tempTable VALUES(9,’3rd’)
INSERT INTO @tempTable VALUES(10,’6th’)

SELECT * FROM @tempTable ORDER BY CAST(LEFT(String_WithN_umericValue,PATINDEX(‘%[^0-9]%’,String_WithN_umericValue)-1) AS INT)


More information about PATINDEX() function can be found at this link.

License

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



Comments and Discussions

 
-- There are no messages in this forum --