sql-server-2005 – 在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
Subquery returned more than 1 value.
This is not permitted when the
subquery follows =,!=,<,<=,>,>=
or when the subquery is used as an
expression.

编辑:

我找到了答案

;with Get_Individual_Chars_Cte AS
( 
   SELECT 
        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

需要帮助

解决方法

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

相关文章

(一)日志传送架构 (1.1)相关服务器 主服务器 :用于生产的服务器,上面运行这生产SQL Server数据库...
(一)事故背景 最近在SQL Server 2012生产数据库上配置完事物复制(发布订阅)后,生产数据库业务出现了...
(一)测试目的 目前公司使用的SQL SERVER 2012高可用环境为主备模式,其中主库可执行读写操作,备库既...
(一)背景个人在使用sql server时,用到了sql server的发布订阅来做主从同步,类似MySQL的异步复制。在...
UNION和OR谓词 找出 product 和 product2 中售价高于 500 的商品的基本信息. select * from product wh...
datawhale组队学习task03