SQL Server 2008 R2:将字符串拆分为单列

时间:2014-10-17 07:25:02

标签: sql-server sql-server-2008-r2

我需要将给定的字符串拆分为单个列。

示例

给定字符串:

'A,B,C,D,E,F'

预期结果:

ColumnA
--------
A
B
C
D
E
F

2 个答案:

答案 0 :(得分:2)

使用custom split() function

CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (colA nvarchar(4000))
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE nvarchar(4000)

SELECT @INDEX = 1
WHILE @INDEX !=0
BEGIN

SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
IF @INDEX !=0

SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING

INSERT INTO @Results(colA) VALUES(@SLICE)

SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)

IF LEN(@STRING) = 0 BREAK
END
RETURN
END

然后运行如下的查询。

SELECT colA FROM [dbo].[Split] ('A,B,C,D,E,F', ',') 


Demo

答案 1 :(得分:0)

declare @commavalue varchar(50)='A,B,C,D,E,F'
select q2.value from
(SELECT cast('<x>'+replace(@commavalue,',','</x><x>')+'</x>' as xml) as Data)q1 CROSS APPLY
(SELECT x.value('.','varchar(100)') as value FROM Data.nodes('x') as f(x))q2