有趣的sql分为两个字符

时间:2012-05-16 19:41:23

标签: sql tsql

我需要为具有两个字符的分割字符串编写函数。 例如:“Hyderabad Hyd,Test”

在上面的字符串中,我需要用空格(“”)和逗号(,)吐出,out结果将保存在表格中

The oputput should be:
Hyderabad
Hyd,Test
Hyd
Test


CREATE function dbo.SplitString   
    (  
        @str nvarchar(4000),   
        @separator char(1)  
    )  
    returns table  

    AS      
    return (  
        with tokens(p, a, b) AS (  
               select   
                1,   
                1,   
                charindex(@separator, @str)  
            union all  
            select  
                p + 1,   
                b + 1,   
                charindex(@separator, @str, b + 1)  
            from tokens  
            where b > 0  
        )  

        select  
            p-1 SNO,  
            substring(  
                @str,   
                a,   
                case when b > 0 then b-a ELSE 4000 end)   
            AS word  
        from tokens  
      )  

Plz帮忙.....

提前致谢..

2 个答案:

答案 0 :(得分:2)

对于您显示的结果,您不需要 new 拆分功能。只是一个采用列表和分隔符的普通文件。

SELECT
  second_split.*
FROM
  dbo.fn_split(@myList, ' ')   AS first_split
CROSS APPLY
(
  SELECT first_split.item
  UNION
  SELECT item FROM dbo.fn_split(first_split.item, ',')
)
  AS second_split

first_split将是HyderabadHyd,Test

第二次分裂将是...... - Hyderabad UNION Hyderabad只是Hyderabad
- 加Hyd,Test UNION HydTest

...给予

  • Hyderabad
  • Hyd,Test
  • Hyd
  • Test

答案 1 :(得分:0)

有几种方法可以做到这一点。您可能希望探索创建SQL CLR,因为它可能更快,更容易地进行您正在寻找的拆分。

http://msdn.microsoft.com/en-us/library/ms254498(v=vs.100).aspx

这是一篇可能有帮助的博文。

http://dataeducation.com/faster-more-scalable-sqlclr-string-splitting/