由逗号分隔到表中的SQL字符串

时间:2017-02-01 02:31:02

标签: sql sql-server string sql-server-2012 sql-server-2008-r2

我有一个以逗号分隔的数字字符串。示例:123, 213, 312, 231 我需要处理SQL游标中的每个数字。所以我的第一步是将每个数字放在一个表中,如下所示:

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

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

注意:我正在使用SQL Server 2012,但如果该功能也支持SQL Server 2008 R2,那将会很不错。

2 个答案:

答案 0 :(得分:3)

rextester:http://rextester.com/ZCU48506

功能:Jeff Moden的Split 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 |
+------------+------+

拆分字符串参考:

答案 1 :(得分: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/