我有一个表中的数据看起来像这样(值得注意的是它不是CSV分离的)
需要将其拆分为单个字符
Data
abcde
想要将其转换为此
Data
a
b
d
c
e
我在互联网上看了但没有找到答案
答案 0 :(得分:6)
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];
答案 1 :(得分:3)
解决问题的上一篇文章:TSQL UDF To Split String Every 8 Characters
将值1传递给@length。
答案 2 :(得分:3)
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
答案 3 :(得分:3)
您可以将表格加入数字列表,然后使用substring
将数据列拆分为行:
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)
答案 4 :(得分:2)
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