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
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
;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