从T-SQL分隔字符串解析整数值的更好方法

时间:2011-07-27 00:59:48

标签: string tsql sql-server-2008 text-parsing delimited-text

我有一个SQLServer2008 R2存储过程,其中包含一个从分隔字符串中解析出整数的算法。

这是我用于循环分隔字符串并提取分隔字符串中可能存在的任何数字的SQL代码示例:

-- Create a delimited list for testing
DECLARE @NumericList nvarchar(MAX) = N'1, 33,44 ,55, foo ,666,77 77,8,bar,9,10'

-- Declare the delimiter
DECLARE @ListDelimiter VARCHAR(1) = ','

-- Remove white space from the list
SET @NumericList = REPLACE(@NumericList, ' ','');

-- Var that will hold the value of the delimited item during the while-loop
DECLARE @NumberInScope VARCHAR(MAX)

WHILE(LEN(@NumericList) > 0)
BEGIN
    -- Get the value to the left of the first delimiter.
    IF(CHARINDEX(@ListDelimiter, @NumericList) > 0)
        SET @NumberInScope = LEFT(@NumericList, CHARINDEX(@ListDelimiter, @NumericList))
    ELSE
        SET @NumberInScope = @NumericList   

    -- Remove the @NumberInScope value from the @NumericList
    SET @NumericList = RIGHT(@NumericList, LEN(@NumericList) - LEN(@NumberInScope))

    -- Remove the delimiter from the @NumberInScope
    SET @NumberInScope = REPLACE(@NumberInScope,@ListDelimiter,'')

    -- Print only the integer values
    IF(ISNUMERIC(@NumberInScope) = 1)
    BEGIN
        PRINT @NumberInScope
    END 
END

上面的代码工作正常,但在查看代码后,在我看来,必须有一个更简洁的方法来做同样的事情。换句话说,是否有任何字符串函数(或者任何新的R2函数,我可能会忽略)我可以实现它会缩小代码并希望更容易阅读?

3 个答案:

答案 0 :(得分:3)

最终文章为"Arrays and Lists in SQL Server 2005 and Beyond"

这里显示了几种分割CSV的方法:CLR,Numbers表,WHILE循环

答案 1 :(得分:2)

以下是代码,您还可以创建“拆分”功能并使用

DECLARE @NumericList nvarchar(max) = N'1, 33,44 ,55, foo ,666,77 77,8,bar,9,10'

;WITH cte as (
SELECT CAST(1 as bigint) p1,  CHARINDEX(',', @NumericList+',') p2, 
CAST(null as Nvarchar(max)) NumberInScope 
UNION ALL
SELECT p2 + 1, CHARINDEX(',',@NumericList+',', p2 + 1), 
SUBSTRING(@NumericList, p1, p2-p1) 
FROM cte WHERE p2>0
)
SELECT NumberInScope from cte WHERE isnumeric(NumberInScope) > 0
OPTION (MAXRECURSION 0)

答案 2 :(得分:1)

从MSSql Server 2016开始,有一个新的关键字引入STRING_SPLIT来执行所需的操作。

SELECT STRING_SPLIT ( string , separator )

参考https://msdn.microsoft.com/en-us/library/mt684588.aspx