Split a string into individual characters in Sql Server 2005

后端 未结 2 1404
猫巷女王i
猫巷女王i 2020-12-17 23:32

Hi I have an input as

ID  data
1   hello
2   sql

The desired output being

ID  RowID  Chars
1    1     H
1    2     e
1            


        
相关标签:
2条回答
  • 2020-12-17 23:48

    Old post but it's worth posting a purely set-based solution. Using NGrams8K you can do this:

    Declare @t table(ID  INT IDENTITY , data varchar(max))
    Insert into @t Select 'hello' union all select 'sql';
    
    SELECT ID, Row_ID = position, [char] = token 
    FROM @t
    CROSS APPLY dbo.NGrams8k(data,1);
    

    Returns:

    ID  Row_ID  char
    --- ------- --------
    1   1       h
    1   2       e
    1   3       l
    1   4       l
    1   5       o
    2   1       s
    2   2       q
    2   3       l
    
    0 讨论(0)
  • 2020-12-18 00:09
    ;with cte as
    (
      select ID,
             substring(data, 1, 1) as Chars,
             stuff(data, 1, 1, '') as data,
             1 as RowID
      from @t
      union all
      select ID,
             substring(data, 1, 1) as Chars,
             stuff(data, 1, 1, '') as data,
             RowID + 1 as RowID
      from cte
      where len(data) > 0
    )
    select ID, RowID, Chars
    from cte
    order by ID, RowID
    
    0 讨论(0)
提交回复
热议问题