如何在SQL中分隔字段并从该字段创建单独的行?

时间:2015-07-20 13:30:23

标签: sql sql-server

我在SQL Server中有一个字段,有时可以包含由Pipe分隔的文本,如下所示:

COLOUR
Red
Blue|Red|Yellow
Green|White
Yellow

我想创造这个:

COLOUR          SUBCOLOUR
Red             Red
Blue|Red|Yellow Blue
Blue|Red|Yellow Red
Blue|Red|Yellow Yellow
Green|White     Green
Green|White     White
Yellow          Yellow

有人有任何想法吗?

由于

2 个答案:

答案 0 :(得分:1)

通过使用split函数,我们可以实现所需的结果集

 declare @t table (Colour  varchar(50))
    insert into @t (Colour)
    values 
    ('Red'),
    ('Blue|Red|Yellow'),
    ('Green|White'),
    ('Yellow')



 ;with cte as (
    SELECT  Colour As Colour ,
         Split.a.value('.', 'VARCHAR(100)') AS SubColour  
     FROM  (SELECT Colour,
             CAST ('<M>' + REPLACE([Colour], '|', '</M><M>') + '</M>' AS XML) AS String  
         FROM  @t) AS A CROSS APPLY String.nodes ('/M') AS Split(a))

         select * from cte 

答案 1 :(得分:0)

未经测试,但有评论。使用变量和游标,因此只会建议如果这不是一个大表而你只做一次。如果这对您不起作用,我很乐意提供更多解释:

CREATE TABLE NewTable (Colour varchar(50),SubColour varchar(50))   

SELECT Colour, LEN(Colour) - LEN(REPLACE(Colour,'|','')) AS delimCount
INTO #temp FROM [ColourTable]

DECLARE @i int
DECLARE @delimLoc int
DECLARE @Colour varchar(50)
DECLARE @subColour varchar(50)
DECLARE ColourCursor CURSOR FOR SELECT * FROM #temp;
OPEN ColourCursor;

逐行走过表

WHILE @@FETCH_STATUS = 0
BEGIN

FETCH NEXT FROM ColourCursor INTO @Colour;
SET @i = 1
SET @delimLoc = 0
IF delimCount > 0

BEGIN
WHILE @i <= delimCount

循环创建一个从最后使用的'|'位置开始的子颜色(如果@i = 1,则为色域的开头)

BEGIN
SET @subColour = SUBSTRING(@Colour,@delimLoc+1,CHARINDEX(@Colour,'|',@delimLoc+1))
INSERT INTO NewTable VALUES (@Colour,@subColour)
SET @i = @i + 1
SET @delimLoc = @delimLoc + CHARINDEX(@Colour,'|',@delimLoc+1)
END

END

END

CLOSE ColourCursor
DEALLOCATE ColourCursor;