Kumar
Kumar

Reputation: 79

T-SQL text sorting

One of column (Say column1 in table Table1) stores data as follow

Column1
test2;test1;test3
test21;test11;test32
--

I want to update this column so that data is stored in sorted form(after splitting the data by ;) as follow

Column1
test1;test2;test3
test11;test21;test32
--

How to write query in a simplest form? I am using SQL Server 2005


Can I assume there is not a simple solution available using T-SQL then I can go with CLR function?

Upvotes: 0

Views: 311

Answers (2)

Ed Harper
Ed Harper

Reputation: 21505

An example of how to do this in T-SQL in a set-based fashion. It assumes that the target table has a PK which uniquely identifies each row.
Note that the sort is text-based. I have added a third line of test data to show this.

DECLARE @t TABLE
(id int ,column1 varchar(50))

INSERT @t
SELECT 1,'test2;test1;test3'
UNION ALL SELECT 2,'test21;test11;test32'
UNION ALL SELECT 3,'test222;test22;test2;test1;test3'

DECLARE @chr_delim char(1)
SET @chr_delim = ';'

;WITH splitCTE
AS
(
SELECT  D.id
        ,SUBSTRING(s,n,CHARINDEX(@chr_delim, s + @chr_delim,n) -n) as ELEMENT
FROM (SELECT id, column1 as s from @t) AS D
JOIN (SELECT ROW_NUMBER() OVER (ORDER BY name) AS n
      FROM master..spt_values
      ) AS nums
ON n <= LEN(s)
AND SUBSTRING(@chr_delim + s,n,1) = @chr_delim
)
UPDATE t
SET column1 = z.col1
FROM @t AS t
JOIN    (
            SELECT DISTINCT id , STUFF(d.x,1,1,'') AS col1
            FROM splitCTE AS r
            CROSS APPLY (SELECT ';' + ELEMENT 
                                 FROM splitCTE AS c 
                                 WHERE c.id = r.id 
                                 ORDER BY ELEMENT FOR XML PATH ('')
                                ) d(x)
        ) AS z
ON z.id = t.id      

SELECT * FROM @t

Upvotes: 1

STO
STO

Reputation: 10638

It is not possible via raw SQL. You can find out implementation of SPLIT function (either T-SQL or CLR) (like http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx that) and process data via temporary converting string list to table, sort it then join back.

Upvotes: 1

Related Questions