我有看起來像這樣的表數據(值得一提的它不是CSV分隔)在MS SQL如何列分成數行無定界符
它需要被分割爲單字符
Data
abcde
想將其轉換爲這個
Data
a
b
d
c
e
我期待在互聯網上,但還沒有找到答案
我有看起來像這樣的表數據(值得一提的它不是CSV分隔)在MS SQL如何列分成數行無定界符
它需要被分割爲單字符
Data
abcde
想將其轉換爲這個
Data
a
b
d
c
e
我期待在互聯網上,但還沒有找到答案
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];
上一篇解決該問題:TSQL UDF To Split String Every 8 Characters
傳遞的值爲1至@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
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
謝謝@Mikael Eriksson,你打敗我來格式化它 –
你可以加入我們的表號的列表,並使用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)
你看這個? http://stackoverflow.com/questions/314824/t-sql-opposite-to-string-concatenation-how-to-split-string-into-multiple-recor –
@瑞克Liddle - 我已經看到,但其設計使用逗號 - 我的數據不是CSV – Rob
您可以指定SQL Server的什麼版本? –