Shilpa Praneesh
Shilpa Praneesh

Reputation: 255

How to sort string alphabetically

I have a table which have the following data

Item
......
xzypq
abdcfe

How can I sort the string in the column and get the following result?

Item
......
pqxyz
abcdef

Upvotes: 2

Views: 2106

Answers (2)

Pரதீப்
Pரதீப்

Reputation: 93724

Using Recursive CTE also you can do this.

SELECT 'xzypq' NAME
INTO   #temp
UNION ALL
SELECT 'abdcfe' 

Recursive CTE

;WITH cte
     AS (SELECT Cast(NAME AS VARCHAR(50)) AS st,NAME AS name1,1 AS rn
         FROM   #temp
         UNION ALL
         SELECT Cast(Substring(NAME, rn, 1) AS VARCHAR(50)),name1,rn + 1
         FROM   cte a
                JOIN #temp b
                  ON a.name1 = b.NAME
                     AND rn < Len(a.name1) + 1)
SELECT DISTINCT (SELECT '' + st
                 FROM   cte b
                 WHERE  a.name1 = b.name1
                        AND rn <> 1
                 ORDER  BY st
                 FOR XML PATH ('')) AS Ordered_String
FROM   cte a
WHERE  rn <> 1 

Result

Ordered_String
--------------
abcdef
pqxyz

Upvotes: 0

Shiljo Paulson
Shiljo Paulson

Reputation: 598

May be try the below link which might help http://social.technet.microsoft.com/wiki/contents/articles/19492.sort-letters-in-a-phrase-using-t-sql.aspx

/*Create sample table*/
IF OBJECT_ID('tempdb..#Text', 'U') IS NOT NULL
DROP TABLE #Test;

CREATE TABLE #Test
(
  ID INT IDENTITY(1, 1) ,
  Phrase VARCHAR(255)
);

/*Populate the table with sample data*/
INSERT  #Test
    ( Phrase )
VALUES 
( 'CHICAGO' ),
( 'NEW YORK' ),
( 'HOUSTON' ),
( 'SAN FRANCISCO' );



/*This is the final solution*/;
WITH    base
      AS ( SELECT   L.[char] ,
                    T.ID ,
                    T.Phrase
           FROM     #Test T
                    CROSS APPLY ( SELECT    SUBSTRING(T.Phrase, 1 + Number, 1) [char]
                                  FROM      master..spt_values
                                  WHERE     Number < DATALENGTH(T.Phrase)
                                            AND type = 'P'
                                ) L
         )
SELECT  DISTINCT
        b1.Phrase ,
        REPLACE(( SELECT    '' + [char]
                  FROM      base b2
                  WHERE     b1.Phrase = b2.Phrase
                  ORDER BY  [char]
                    FOR
                      XML PATH('')
                ), '&#x20;', ' ') AS columns2
FROM    base AS b1;

Upvotes: 2

Related Questions