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
abcd开发者_C百科e
want to convert it to this
Data
a
b
d
c
e
I have looked on the internet but have not found the answer
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];
Previous post that solves the problem: TSQL UDF To Split String Every 8 Characters
Pass a value of 1 to @length.
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
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)
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
精彩评论