将逗号分隔列值转换为行

时间:2022-06-14 00:19:29

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..

我需要像...那样的输出

Id   | processedrows
--------------
1     abc
1     def
1     ghi
2     jkl
2     mno
2     pqr

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

如何在SQL Server中使用select查询执行相同的操作?

4 个解决方案

#1


48  

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

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

#2


0  

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)

#3


0  

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

#4


0  

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)

#1


48  

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

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

#2


0  

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)

#3


0  

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

#4


0  

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)