2011-06-16 82 views
7

嗨單個字符我有一個​​輸入爲分割字符串轉換成SQL Server 2005中

ID data 
1 hello 
2 sql 

所需的輸出是

ID RowID Chars 
1 1  H 
1 2  e 
1 3  l 
1 4  l 
1 5  o 
2 1  s 
2 2  q 
2 3  l 

我的做法至今被

Declare @t table(ID INT IDENTITY , data varchar(max)) 
Insert into @t Select 'hello' union all select 'sql' 
--Select * from @t 
;With CteMaxlen As(
Select MaxLength = max(len(data)) from @t) 
, Num_Cte AS 
(  
     SELECT 1 AS rn 
     UNION ALL 
     SELECT rn +1 AS rn 
     FROM Num_Cte 
     WHERE rn <(select MaxLength from CteMaxlen) 
) 
-- Shred into individual characters 
, Get_Individual_Chars_Cte AS 
( 
     SELECT 
      ID 
      ,Row_ID =ROW_NUMBER() Over(PARTITION by ID Order by ID) 
      ,chars    
     FROM @t,Num_Cte 
     CROSS APPLY(SELECT SUBSTRING((select data from @t),rn,1) AS chars) SplittedChars  
) 

Select * from Get_Individual_Chars_Cte 

的查詢根本不起作用,例外是

Msg 512,Level 16,State 1,Line 4
子查詢返回多個值。 當 子查詢遵循=,!=,<,< =,>,> = 或當子查詢用作 表達式時,這是不允許的。

編輯:

我發現我的答案

;with Get_Individual_Chars_Cte AS 
( 
    SELECT 
     ID, 
     Row_ID =ROW_NUMBER() Over(PARTITION by ID Order by ID) 
     ,SUBSTRING(Data,Number,1) AS [Char]--, 

FROM @t 
INNER JOIN master.dbo.spt_values ON 
Number BETWEEN 1 AND LEN(Data) 
AND type='P' 

) 

Select * from Get_Individual_Chars_Cte 

幫助需要

回答

2
;with cte as 
(
    select ID, 
     substring(data, 1, 1) as Chars, 
     stuff(data, 1, 1, '') as data, 
     1 as RowID 
    from @t 
    union all 
    select ID, 
     substring(data, 1, 1) as Chars, 
     stuff(data, 1, 1, '') as data, 
     RowID + 1 as RowID 
    from cte 
    where len(data) > 0 
) 
select ID, RowID, Chars 
from cte 
order by ID, RowID 
+0

其實我answerd我自己的問題,因爲在我有少點聲望值,在格蘭質疑體中提到的編輯部分。但謝謝你的答案,我會接受你的,但我的工作也很好。我請求,因爲你有更多的聲譽,你有可能拿出我的答案並粘貼答案部分?如果是這樣,如果您覺得我的回答與您的回答一樣正確,請做好必要的工作。 – aditi 2011-06-16 05:53:59

+0

@aditi - 你應該能夠回答你自己的問題。代表100以下的用戶可能會有一個時間限制(8小時?)。在常見問題解答中找不到它,但我記得閱讀過這些內容。 48小時後,您可以**接受**自己的答案。 – 2011-06-16 06:15:06

0

老的文章,但它是值得發佈一個純粹的基於集的解決方案。使用NGrams8K你可以這樣做:

Declare @t table(ID INT IDENTITY , data varchar(max)) 
Insert into @t Select 'hello' union all select 'sql'; 

SELECT ID, Row_ID = position, [char] = token 
FROM @t 
CROSS APPLY dbo.NGrams8k(data,1); 

返回:

ID Row_ID char 
--- ------- -------- 
1 1  h 
1 2  e 
1 3  l 
1 4  l 
1 5  o 
2 1  s 
2 2  q 
2 3  l