2017-02-01 4 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/

関連する問題