Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Split Word into characters

Tags:

string

tsql

split

I have searched everywhere and I cannot find this implementation anywhere.

Let's say I have the word: QWERTY

I want to obtain this table:

Q
W
E
R
T
Y

Or for QWERTY AnotherWord I want to obtain

Q
W
E
R
T
Y
[space character here]
A
n
o
t
h
e
r
W
o
r
d
like image 866
Dragos Durlut Avatar asked Dec 15 '11 09:12

Dragos Durlut


2 Answers

Do it like this:

select substring(a.b, v.number+1, 1) 
from (select 'QWERTY AnotherWord' b) a
join master..spt_values v on v.number < len(a.b)
where v.type = 'P'
like image 91
t-clausen.dk Avatar answered Nov 10 '22 09:11

t-clausen.dk


Declare @word nvarchar(max)
Select @word = 'Hello This is the test';

with cte (Number)as 
(Select 1
union all 
select Number +1 From cte  where number <len(@word)
)
select * from Cte Cross apply (Select SUBSTRING(@word,number,1 ) ) as J(Letter)
like image 8
BabiBN Avatar answered Nov 10 '22 10:11

BabiBN