使用拆分功能可以在单独的行中显示每个值

时间:2017-12-18 09:52:35

标签: sql sql-server split sql-server-2014

考虑一下我已经创建了dbo.split函数,其运行方式如下:

查询:

select substr from dbo.split(',' , 'A,B,C')

结果:

|Substr|
--------
|A     |
--------
|B     |
--------
|C     |
--------

现在我想使用此函数转换此表:

|ID|Char|
---------
|1 |A,B |
---------
|2 |A   |
---------
|3 |B,C |
---------

到这个结果:

|ID|Char|
---------
|1 |A   |
---------
|1 |B   |
---------
|2 |A   |
---------
|3 |B   |
---------
|3 |C   |
---------

2 个答案:

答案 0 :(得分:2)

试试这个:

这没有Split功能。

 DECLARE @Table TABLE(ID INT, [Char] VARCHAR(20))
 INSERT INTO @Table VALUES(1,'A,B')
 INSERT INTO @Table VALUES(2,'A')
 INSERT INTO @Table VALUES(3,'B,C')

SELECT A.ID,  
     Split.a.value('.', 'VARCHAR(100)') AS [Char]  
 FROM  
 (
     SELECT ID,  
         CAST ('<M>' + REPLACE([Char], ',', '</M><M>') + '</M>' AS XML) AS Data  
     FROM  @Table
 ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);

答案 1 :(得分:0)

由于您已经拥有dbo.split函数,因此可以使用CROSS APPLY获得所需的输出:

DECLARE @tmp TABLE(ID INT, [Char] VARCHAR(50))
INSERT INTO @tmp VALUES(1,'A,B'), (2,'A'), (3,'B,C')

select T.[ID], D.[Substr] 
from @tmp T cross apply [dbo].[Split](',', T.[Char]) D

结果:

enter image description here