Rob
Rob

Reputation: 1255

In MS SQL how to split a column into rows with no delimiter

I have data in a table which looks like this (worth noting its not CSV seperated)

It needs to be split in to single chars

Data
abcde

want to convert it to this

Data
a
b
d
c
e

I have looked on the internet but have not found the answer

Upvotes: 4

Views: 2821

Answers (5)

Matt Evans
Matt Evans

Reputation: 7575

declare @input varchar(max);
set @input = 'abcde'

declare @table TABLE (char varchar(1));


while (LEN(@input)> 0)
begin
insert into @table select substring(@input,1,1)
select @input = RIGHT(@input,Len(@input)-1) 
end

select * from @table

Upvotes: 2

Andomar
Andomar

Reputation: 238048

You could join the table to a list of numbers, and use substring to split data column into rows:

declare @YourTable table (data varchar(50))
insert @YourTable 
          select 'abcde' 
union all select 'fghe'

; with  nrs as
        (
        select  max(len(data)) as i
        from    @YourTable
        union all
        select  i - 1
        from    nrs
        where   i > 1
        )
select  substring(yt.data, i, 1)
from    nrs
join    @YourTable yt
on      nrs.i < len(yt.data)
option  (maxrecursion 0)

Upvotes: 3

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

declare @T table
(
  ID int identity,
  Data varchar(10)
)

insert into @T
select 'ABCDE' union 
select '12345'

;with cte as 
(
  select ID,
         left(Data, 1) as Data,
         stuff(Data, 1, 1, '') as Rest
  from @T
  where len(Data) > 0
  union all
  select ID,
         left(Rest, 1) as Data,
         stuff(Rest, 1, 1, '') as Rest
  from cte
  where len(Rest) > 0
)
select ID,
       Data
from cte
order by ID

Upvotes: 3

Rick Liddle
Rick Liddle

Reputation: 2714

Previous post that solves the problem: TSQL UDF To Split String Every 8 Characters

Pass a value of 1 to @length.

Upvotes: 3

Aaron Bertrand
Aaron Bertrand

Reputation: 280252

CREATE FUNCTION dbo.SplitLetters
(
    @s NVARCHAR(MAX)
)
RETURNS @t TABLE
(
    [order] INT,
    [letter] NCHAR(1)
)
AS
BEGIN
    DECLARE @i INT;
    SET @i = 1;
    WHILE @i <= LEN(@s)
    BEGIN
        INSERT @t SELECT @i, SUBSTRING(@s, @i, 1);
        SET @i = @i + 1;
    END
    RETURN;
END
GO

SELECT [letter]
    FROM dbo.SplitLetters(N'abcdefgh12345 6 7')
    ORDER BY [order];

Upvotes: 6

Related Questions