Reputation: 11
I want sort the below Alphanumeric Column in SQL Server.
Column A
------------------------------
SP-SS-2
SP-FAB-8
WD-1
WD-4A
WD-11
WD-10
WD-2
WD-20
I want sorted by ascending order Output is as follows:
Column A
-----------------------
SP-FAB-8
SP-SS-2
WD-1
WD-2
WD-4A
WD-10
WD-11
WD-20
Any tricks to make it sort properly?
Upvotes: 0
Views: 128
Reputation: 1522
SELECT ColumnA FROM #TblTableA
ORDER BY
LEFT(ColumnA,PATINDEX('%[0-9]%',ColumnA)-1),
CASE
WHEN ISNUMERIC(ColumnA) = 0
THEN CAST(LEFT(RIGHT(ColumnA,LEN(ColumnA)-CHARINDEX('-',ColumnA)),
patindex('%[^0-9]%', RIGHT(ColumnA,LEN(ColumnA)-CHARINDEX('-',ColumnA))+'.') - 1) AS INT)
ELSE ColumnA
END
Output:-
ColumnA
---------
SP-FAB-8
SP-SS-2
WD-1
WD-2
WD-4A
WD-10
WD-11
WD-20
Note:- You will get this type of output using Patindex.....
For More Info...Follow this below Link https://dba.stackexchange.com/questions/117379/sort-a-varchar-type-column-alphanumeric-values
Upvotes: 2
Reputation: 1744
If we want to overcome this issue, we need to separate strings and numbers and then sort them. In the first step we need a function that helps to separate numbers from the strings. Therefore, we will create this function Query to get only numbers from a string
CREATE FUNCTION dbo.udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END
GO
In the second step we can execute the following query that will help to sort alphanumeric characters.
CREATE TABLE #Temp
(Val VARCHAR(100))
INSERT INTO #Temp
VALUES ('SP-SS-2') ,
('SP-FAB-8'),
('WD-1'),
('WD-4A'),
('WD-11'),
('WD-10'),
('WD-2'),
('WD-20')
select val,dbo.udf_GetNumeric(val) as textpart
,LEFT(val,PATINDEX('%[0-9]%',val)-1) as stringpart
from
#Temp
order by LEFT(val,PATINDEX('%[0-9]%',val)-1) ,convert(int,dbo.udf_GetNumeric(val))
+----------+----------+------------+
| val | textpart | stringpart |
+----------+----------+------------+
| SP-FAB-8 | 8 | SP-FAB- |
| SP-SS-2 | 2 | SP-SS- |
| WD-1 | 1 | WD- |
| WD-2 | 2 | WD- |
| WD-4A | 4 | WD- |
| WD-10 | 10 | WD- |
| WD-11 | 11 | WD- |
| WD-20 | 20 | WD- |
+----------+----------+------------+
Upvotes: 2