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    3     l
1    4     l
1    5     o
2    1     s
2    2     q
2    3     l
My approach so far being
Declare @t table(ID  INT IDENTITY , data varchar(max))
Insert into @t Select 'hello' union all select 'sql'
--Select * from @t
;With CteMaxlen As(
Select MaxLength = max(len(data)) from @t)
, Num_Cte AS
(     
      SELECT 1 AS rn
      UNION ALL
      SELECT rn +1 AS rn 
      FROM Num_Cte 
      WHERE rn <(select MaxLength from CteMaxlen)
)
-- Shred into individual characters
, Get_Individual_Chars_Cte AS
( 
      SELECT  
            ID
            ,Row_ID =ROW_NUMBER() Over(PARTITION by ID Order by ID)
            ,chars               
      FROM @t,Num_Cte
      CROSS APPLY( SELECT SUBSTRING((select data from  @t),rn,1)  AS chars) SplittedChars       
)
Select * from Get_Individual_Chars_Cte 
The query is not working at all with an exception being
Msg 512, Level 16, State 1, Line 4
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Edit :
I found my answer
;with Get_Individual_Chars_Cte AS
( 
   SELECT 
        ID,
        Row_ID =ROW_NUMBER() Over(PARTITION by ID Order by ID) 
        ,SUBSTRING(Data,Number,1) AS [C开发者_开发百科har]--,
FROM @t  
INNER JOIN master.dbo.spt_values ON
 Number BETWEEN 1 AND LEN(Data)
 AND type='P'
)
Select * from Get_Individual_Chars_Cte 
Help needed
;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
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
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论