我想把'1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 ......'(逗号分隔)拆分成表或表变量.
有没有人有一个函数可以连续返回每一个?
试试这个
DECLARE @xml xml, @str varchar(100), @delimiter varchar(10) SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15' SET @delimiter = ',' SET @xml = cast((''+replace(@str, @delimiter, ' ')+' ') as xml) SELECT C.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as X(C)
要么
DECLARE @str varchar(100), @delimiter varchar(10) SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15' SET @delimiter = ',' ;WITH cte AS ( SELECT 0 a, 1 b UNION ALL SELECT b, CHARINDEX(@delimiter, @str, b) + LEN(@delimiter) FROM CTE WHERE b > a ) SELECT SUBSTRING(@str, a, CASE WHEN b > LEN(@delimiter) THEN b - a - LEN(@delimiter) ELSE LEN(@str) - a + 1 END) value FROM cte WHERE a > 0
还有很多方法可以做到这一点如何拆分逗号分隔的字符串?
这是一个老式的解决方案:
/* Splits string into parts delimitered with specified character. */ CREATE FUNCTION [dbo].[SDF_SplitString] ( @sString nvarchar(2048), @cDelimiter nchar(1) ) RETURNS @tParts TABLE ( part nvarchar(2048) ) AS BEGIN if @sString is null return declare @iStart int, @iPos int if substring( @sString, 1, 1 ) = @cDelimiter begin set @iStart = 2 insert into @tParts values( null ) end else set @iStart = 1 while 1=1 begin set @iPos = charindex( @cDelimiter, @sString, @iStart ) if @iPos = 0 set @iPos = len( @sString )+1 if @iPos - @iStart > 0 insert into @tParts values ( substring( @sString, @iStart, @iPos-@iStart )) else insert into @tParts values( null ) set @iStart = @iPos+1 if @iStart > len( @sString ) break end RETURN END
在SQL Server 2008中,您可以使用.NET代码实现相同的功能.也许它可以更快地工作,但绝对这种方法更容易管理.
您已经标记了此SQL Server 2008,但此问题的未来访问者(使用SQL Server 2016+)可能希望了解STRING_SPLIT
.
使用这个新的内置功能,您现在可以使用
SELECT TRY_CAST(value AS INT) FROM STRING_SPLIT ('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15', ',')
这个功能的一些限制和一些有前途的性能测试结果在Aaron Bertrand的博客文章中.
对于那些熟悉该功能的人来说,这就像.NET一样:
CREATE FUNCTION dbo.[String.Split] ( @Text VARCHAR(MAX), @Delimiter VARCHAR(100), @Index INT ) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @A TABLE (ID INT IDENTITY, V VARCHAR(MAX)); DECLARE @R VARCHAR(MAX); WITH CTE AS ( SELECT 0 A, 1 B UNION ALL SELECT B, CONVERT(INT,CHARINDEX(@Delimiter, @Text, B) + LEN(@Delimiter)) FROM CTE WHERE B > A ) INSERT @A(V) SELECT SUBSTRING(@Text,A,CASE WHEN B > LEN(@Delimiter) THEN B-A-LEN(@Delimiter) ELSE LEN(@Text) - A + 1 END) VALUE FROM CTE WHERE A >0 SELECT @R = V FROM @A WHERE ID = @Index + 1 RETURN @R END SELECT dbo.[String.Split]('121,2,3,0',',',1) -- gives '2'
这是你问的分裂功能
CREATE FUNCTION [dbo].[split]( @delimited NVARCHAR(MAX), @delimiter NVARCHAR(100) ) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX)) AS BEGIN DECLARE @xml XML SET @xml = N'' + REPLACE(@delimited,@delimiter,' ') + ' ' INSERT INTO @t(val) SELECT r.value('.','varchar(MAX)') as item FROM @xml.nodes('/t') as records(r) RETURN END
执行这样的功能
select * from dbo.split('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15',',')