A better way to parse integer values from a T-SQL delimited string

前端 未结 3 1494
醉梦人生
醉梦人生 2021-01-16 05:21

I have a SQLServer2008 R2 Stored Procedure that contains an algorithm for parsing out integers from a delimited string.

Here\'s an example of the SQL code that I mad

相关标签:
3条回答
  • 2021-01-16 05:23

    Here is the code, you can also create a 'split' function and use that

    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)
    
    0 讨论(0)
  • 2021-01-16 05:27

    The definitive article is "Arrays and Lists in SQL Server 2005 and Beyond"

    Here several methods are shown for splitting CSVs: CLR, Numbers table, WHILE loops

    0 讨论(0)
  • 2021-01-16 05:31

    From MSSql Server 2016, there is a new keyword introduced STRING_SPLIT to do the desired operation.

    SELECT STRING_SPLIT ( string , separator )
    

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

    0 讨论(0)
提交回复
热议问题