2011-07-08 33 views
4

我有看起來像這樣的表數據(值得一提的它不是CSV分隔)在MS SQL如何列分成數行無定界符

它需要被分割爲單字符

Data 
abcde 

想將其轉換爲這個

Data 
a 
b 
d 
c 
e 

我期待在互聯網上,但還沒有找到答案

+0

你看這個? http://stackoverflow.com/questions/314824/t-sql-opposite-to-string-concatenation-how-to-split-string-into-multiple-recor –

+0

@瑞克Liddle - 我已經看到,但其設計使用逗號 - 我的數據不是CSV – Rob

+0

您可以指定SQL Server的什麼版本? –

回答

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]; 
+0

太棒了!謝謝! – Rob

+0

+1 - 不錯的一個Aaron – JNK

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 
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 
+1

謝謝@Mikael Eriksson,你打敗我來格式化它 –

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)