2017-02-01 98 views
0

我有一个由逗号分隔的数字字符串。示例:123, 213, 312, 231 而且我需要处理SQL游标中的每个数字。所以我的第一步是把每个数字在表像这样:通过逗号分隔的SQL字符串表

DECLARE @t AS TABLE(string nvarchar(100)); 

但问题是我不知道该如何分割字符串,删除逗号和我在创建的表中插入的每个号码同时。我可以尝试猴子尝试硬编码,但我知道它不会美丽而快速。请帮帮我!

注意:我正在使用SQL Server 2012,但如果该函数也支持SQL Server 2008 R2,它将会很好。

回答

3

rextester:http://rextester.com/ZCU48506

功能:杰夫MODEN的分裂N4k

create function dbo.DelimitedSplitN4K (
    @pString nvarchar(4000) 
    , @pDelimiter nchar(1) 
) 
returns table with schemabinding as 
return 
    with e1(n) as (
    select 1 union all select 1 union all select 1 union all 
    select 1 union all select 1 union all select 1 union all 
    select 1 union all select 1 union all select 1 union all select 1 
) 
    , e2(n) as (select 1 from e1 a, e1 b) 
    , e4(n) as (select 1 from e2 a, e2 b) 
    , cteTally(n) as (select top (isnull(datalength(@pString)/2,0)) 
     row_number() over (order by (select null)) from e4) 
    , cteStart(n1) as (select 1 union all 
     select t.n+1 from cteTally t where substring(@pString,t.n,1) = @pDelimiter) 
    , cteLen(n1,l1) as(select s.n1 
    , isnull(nullif(charindex(@pDelimiter,@pString,s.n1),0)-s.n1,4000) 
    from cteStart s 
) 
select ItemNumber = row_number() over(order by l.n1) 
     , Item  = substring(@pString, l.n1, l.l1) 
    from cteLen l; 
go 

查询:

declare @sample nvarchar (64) = '123,213,312,231' 

select * from dbo.DelimitedSplitN4K(@sample,',') 

结果

+------------+------+ 
| ItemNumber | Item | 
+------------+------+ 
|   1 | 123 | 
|   2 | 213 | 
|   3 | 312 | 
|   4 | 231 | 
+------------+------+ 

分割字符串参考:

+0

哇,这看起来不可思议。非常感谢链接这个自定义工具!将标记为答案 –

0

您可以使用XML功能,因为它的速度更快。

首先,创建功能:

CREATE FUNCTION stringDilimitedToTableXML 
( 
    @str VARCHAR(4000), 
    @delimiter nchar(1) 
) 
RETURNS @Result TABLE(Value BIGINT) 
AS 
BEGIN 

    Declare @x XML 
    select @x = cast('<A>' + replace(@str,@delimiter,'</A><A>') + '</A>' as xml) 

    INSERT INTO @Result 
     SELECT t.value('.', 'int') as inVal 
     FROM @x.nodes('/A') as x(t) 

    RETURN 

END 
GO 

呼叫查询功能:

DECLARE @str VARCHAR(4000) = '2879,2880,2881,2892,2893,2894' 

SELECT * FROM dbo.stringDilimitedToTableXML(@str, ',') 

结果:

Value 
-------------------- 
2879 
2880 
2881 
2892 
2893 
2894 

(6 row(s) affected) 

链接:https://blogs.msdn.microsoft.com/amitjet/2009/12/11/convert-comma-separated-string-to-table-4-different-approaches/