在SQL Server中以逗号分隔的字符串到表的列中

在SQL Server中以逗号分隔的字符串到表的列中,第1张

在SQL Server中以逗号分隔的字符串到表的列中

创建一个函数:

CREATE FUNCTION [dbo].[Split](@String nvarchar(4000), @Delimiter char(1))RETURNS @Results TABLE (Items nvarchar(4000))ASBEGIN    DECLARE @Index INT    DECLARE @Slice nvarchar(4000)    -- HAVE TO SET TO 1 SO IT DOESN鈥橳 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    RETURNEND

将字符串

@str
和定界符(,)传递给函数。

SELECT Items FROM [dbo].[Split] (@str, ',')

它将结果返回为表格:

Items0.000.001576.950.004105.881017.870.006700.70

参见 SQL Fiddle



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5107443.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存