我正在使用SQL Server,我已成功将表的行转换为逗号分隔值,现在我想将该逗号分隔值的字符串转换回表的行。
我有这个字符串(Varchar
)
DECLARE @str AS varchar(Max)
SET @str = '0.00,0.00,1576.95,0.00,4105.88,1017.87,0.00,6700.70'
我希望这些值成行。
像
0.00
0.00
1576
...
答案 0 :(得分:1)
这个问题与其他几个问题重复,但是一些已接受的答案仍然是低效的WHILE循环或递归CTE。有三种方法可以实现不会破坏性能的拆分:
数字/理货表: http://www.sqlservercentral.com/articles/Tally+Table/72993/(免费 需要注册)
XML: https://www.simple-talk.com/blogs/2012/01/05/using-xml-to-pass-lists-as-parameters-in-sql-server/
SQLCLR:在很多网站上有很多这样的例子,但你的 最好(也是最简单)的赌注是要么抓住提供的那个 上面提到的Numbers / Tally Table文章或只是安装SQL# (SQLsharp)(我是SQL#的作者,但String_Split和String_Split4k在 免费版)。
答案 1 :(得分:0)
创建一个函数:
CREATE FUNCTION [dbo].[Split](@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000))
AS
BEGIN
DECLARE @Index INT
DECLARE @Slice nvarchar(4000)
-- HAVE TO SET TO 1 SO IT DOESN’T EQUAL ZERO FIRST TIME IN LOOP
SELECT @Index = 1
WHILE @Index !=0
BEGIN
SELECT @Index = CHARINDEX(@Delimiter,@String) --Getting the indexof the first Occurrence of the delimiter
-- Saving everything to the left of the delimiter to the variable SLICE
IF @Index !=0
SELECT @Slice = LEFT(@String,@Index - 1)
ELSE
SELECT @Slice = @String
-- Inserting the value of Slice into the Results SET
INSERT INTO @Results(Items) VALUES(@Slice)
--Remove the Slice value from Main String
SELECT @String = RIGHT(@String,LEN(@String) - @Index)
-- Break if Main String is empty
IF LEN(@String) = 0 BREAK
END
RETURN
END
将字符串@str
和分隔符(,)传递给函数。
SELECT Items FROM [dbo].[Split] (@str, ',')
它会将结果作为表格返回:
Items
0.00
0.00
1576.95
0.00
4105.88
1017.87
0.00
6700.70
请参阅SQL Fiddle
答案 2 :(得分:0)
尝试此功能
CREATE FUNCTION UF_CSVToTable_new(@psCSString VARCHAR(8000))
RETURNS @otTemp TABLE(sID VARCHAR(20))
AS
BEGIN
DECLARE @sTemp VARCHAR(10)
WHILE LEN(@psCSString) > 0
BEGIN
SET @sTemp = LEFT(@psCSString, ISNULL(NULLIF(CHARINDEX(',', @psCSString) - 1, -1),
LEN(@psCSString)))
SET @psCSString = SUBSTRING(@psCSString,ISNULL(NULLIF(CHARINDEX(',', @psCSString), 0),
LEN(@psCSString)) + 1, LEN(@psCSString))
INSERT INTO @otTemp VALUES (@sTemp)
END
RETURN
END
用法
DECLARE @str AS varchar(Max)
SET @str = '0.00,0.00,1576.95,0.00,4105.88,1017.87,0.00,6700.70'
SELECT * FROM UF_CSVToTable_new(@str)
<强>结果强>