Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 683
Rob Avatar asked Dec 03 '22 07:12

Rob


2 Answers

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];
like image 71
Aaron Bertrand Avatar answered Jan 06 '23 06:01

Aaron Bertrand


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

Pass a value of 1 to @length.

like image 33
Rick Liddle Avatar answered Jan 06 '23 06:01

Rick Liddle