SQL Server Convert Comma Separated column value to rows

o2rvlv0m  于 2023-08-02  发布在  其他
关注(0)|答案(5)|浏览(110)

I have a table Sample with data stored like below
| Id | String |
| ------------ | ------------ |
| 1 | abc,def,ghi |
| 2 | jkl,mno,pqr |

I need the output like..

Idprocessedrows
1abc
1def
1ghi
2jkl
2mno
2pqr

How can I do the same with a select query in SQL Server?

2g32fytz

2g32fytz1#

try this

SELECT A.[id],  
     Split.a.value('.', 'VARCHAR(100)') AS String  
 FROM  (SELECT [id],  
         CAST ('<M>' + REPLACE([string], ',', '</M><M>') + '</M>' AS XML) AS String  
     FROM  TableA) AS A CROSS APPLY String.nodes ('/M') AS Split(a);

refer here

http://www.sqljason.com/2010/05/converting-single-comma-separated-row.html

blmhpbnm

blmhpbnm2#

SELECT EmployeeID,
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Certs
FROM
(
SELECT EmployeeID,CAST('<XMLRoot><RowData>' + REPLACE(Certs,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
FROM   @t
)t
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
qvtsj1bj

qvtsj1bj3#

New way of doing this:

SELECT
         a.Id,
         b.value
    FROM
         Sample a 
         cross apply string_split(a.string,',') b
7dl7o3gd

7dl7o3gd4#

Try with this. You will get your output.

SELECT id,
PARSENAME(REPLACE(Split.a.value('.', 'VARCHAR(100)'),'-','.'),1) 'Values' 
FROM  
(
     SELECT algorithms,
     CAST ('<M>' + REPLACE(string, ',', '</M><M>') + '</M>' AS XML) AS Data 
     FROM   <TableName> 
) AS A 
CROSS APPLY Data.nodes ('/M') AS Split(a)
v1uwarro

v1uwarro5#

Let's try the below script:-

declare @str varchar(max)

SELECT @str = isnull(@str +',', '') + a.Value
FROM (SELECT Value Entityvalue from Table) a

select @str

相关问题