【问题标题】:Splitting the string in sql server在sql server中拆分字符串
【发布时间】:2014-02-21 02:38:49
【问题描述】:

我在数据库中有一个逗号分隔的字符串。像 '苹果、香蕉、菠萝、葡萄' 我需要在逗号的基础上拆分这个字符串并遍历这个。由于sql server中没有内置函数,有没有什么有效的方法可以实现这个目标。

【问题讨论】:

  • 你使用什么服务器端语言?

标签: sql sql-server database string


【解决方案1】:

试试这个功能

CREATE FUNCTION [dbo].[func_Split] 
    (   
    @DelimitedString    varchar(8000),
    @Delimiter              varchar(100) 
    )
RETURNS @tblArray TABLE
    (
    ElementID   int IDENTITY(1,1),  -- Array index
    Element     varchar(1000)               -- Array element contents
    )
AS
BEGIN

    -- Local Variable Declarations
    -- ---------------------------
    DECLARE @Index      smallint,
                    @Start      smallint,
                    @DelSize    smallint

    SET @DelSize = LEN(@Delimiter)

    -- Loop through source string and add elements to destination table array
    -- ----------------------------------------------------------------------
    WHILE LEN(@DelimitedString) > 0
    BEGIN

        SET @Index = CHARINDEX(@Delimiter, @DelimitedString)

        IF @Index = 0
            BEGIN

                INSERT INTO
                    @tblArray 
                    (Element)
                VALUES
                    (LTRIM(RTRIM(@DelimitedString)))

                BREAK
            END
        ELSE
            BEGIN

                INSERT INTO
                    @tblArray 
                    (Element)
                VALUES
                    (LTRIM(RTRIM(SUBSTRING(@DelimitedString, 1,@Index - 1))))

                SET @Start = @Index + @DelSize
                SET @DelimitedString = SUBSTRING(@DelimitedString, @Start , LEN(@DelimitedString) - @Start + 1)

            END
    END

    RETURN
END

示例用法 - 只需将逗号分隔的字符串以及所需的分隔符传递给函数。

DECLARE @SQLStr varchar(100)
SELECT @SQLStr = 'Mickey Mouse, Goofy, Donald Duck, Pluto, Minnie Mouse'

SELECT
    *
FROM
    dbo.func_split(@SQLStr, ',')

结果会是这样的

【讨论】:

  • 我会使用SET @DelSize = LEN(@Delimiter + 'x') - 1 来处理带有尾随空格的分隔符,例如' ' 和', '。
  • 非常感谢 Vignesh Kumar,帮了大忙!
  • @ChryCheng - 这绝对是这个解决方案中应该包含的内容。
  • 我知道这已经相当老了 - 但仍然感谢。我唯一遇到的问题是子字符串嵌入了转义分隔符,例如"Mickey\,Mouse, Goofy..." - 这会将 "Mickey\" 和 "Mouse" 一分为二 - 但应该只给我 "Mickey,Mouse" 作为一个
【解决方案2】:

您可以将数据转换为 XML,方法是将逗号替换为自定义标记,在本例中,<w> 表示单词。

create table t(col varchar(255));
insert into t values ('apple,banana,pineapple,grapes');
insert into t values ('car,bike,airplane');

select cast(('<w>' + replace(col, ',', '</w><w>') + '</w>') as xml) as xmlValue
  from t

返回

|                                               XMLVALUE |
|--------------------------------------------------------|
| <w>apple</w><w>banana</w><w>pineapple</w><w>grapes</w> |
|                   <w>car</w><w>bike</w><w>airplane</w> |

现在,如果您将此查询用作内部 xml 选择,则外部查询可以将其拆分为不同的行:

解决方案:

select split.xmlTable.value('.', 'varchar(255)') as xmlValue
from (

   select cast(('<w>' + replace(col, ',', '</w><w>') + '</w>') as xml) as xmlValue
     from t

) as xmlTable
cross apply xmlValue.nodes ('/w') as split(xmlTable);

Live sqlFiddle

【讨论】:

    【解决方案3】:

    ...由于sql server中没有内置函数...

    在您提出这个问题时确实如此,但 SQL Server 2016 引入了STRING_SPLIT。

    所以你可以使用

    SELECT value
    FROM   STRING_SPLIT ('apple,banana,pineapple,grapes', ',') 
    

    有一些限制(仅接受单个字符分隔符,并且缺少任何表示拆分索引最引人注目的列)。性能测试的各种限制和一些有希望的结果在this blog post by Aaron Bertrand。

    【讨论】:

      【解决方案4】:

      我有一个使用递归的解决方案,如下所示

      Create function split_string(@str as nvarchar(max),@separator as char(1)) returns @myvalues Table (id int identity(1,1),myval nvarchar(100))
      as 
      --Kamel Gazzah
      --23/04/2019
      begin
      with cte as(
      select @str [mystr],
      cast(1 as int) [Start],
      charindex(@separator,@str)as Nd
      union all
      select substring(@str,nd+1,len(@str)),cast(Nd+1 as int),charindex(@separator,@str,Nd+1) from cte
      where nd>0
      )
      insert into @myvalues(myval) 
      select case when nd>0 then substring(@str,start,Nd-start) 
      else substring(@str,start,len(@str)) end [splitted] 
      from cte   OPTION (MAXRECURSION 1000);
      return ;
      end;
      

      你可以调用这个函数

      select * from split_string('apple,banana,pineapple,grapes',',')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-26
        • 2014-06-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多