我也有啊。这个帖子我也试过了。一样的。 这个例子 需要对2列分别进行拆分。
必须要分别拆分。然后进行连接。不能一起。
我当时 代码这样
select code2,
SUBSTRING(t.[code], number ,CHARINDEX(',',t.[code]+',',number)-number) as code
from cte t,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING(','+t.[code],s.number,1) = ',' or SUBSTRING(','+t.[code2],s.number,1) = ','
一样报这个错误。因为对于CODE2来说他的CHARINDEX(',',t.[code2]+',',number)=10,
用来来截断CODE 就会报错啊LEN(code)<10
必须要分别拆分。然后进行连接。不能一起。
我当时 代码这样
select code2,
SUBSTRING(t.[code], number ,CHARINDEX(',',t.[code]+',',number)-number) as code
from cte t,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING(','+t.[code],s.number,1) = ',' or SUBSTRING(','+t.[code2],s.number,1) = ','
一样报这个错误。因为对于CODE2来说他的CHARINDEX(',',t.[code2]+',',number)=10,
用来来截断CODE 就会报错啊LEN(code)<10
然后再
select * from #t where c>0就不抱错了,因为不需要重新计算charindex(code,code2)
不好意思 我看错了。你这个报错和我的一样。但是写法不一样。
你先把最后的CTE1结果插入到一个表里面。然后再从这个里面进行SELECT就不会报错。
所以 我觉得原因应该是CTE不会提高性能。只能方便阅读。
所以 SUBSTRING(','+t.[code],s.number,1) = ',' 这个条件和CHARINDEX(code,code2)>0
没有先后问题。
不报错。加了就溢出。
select
v,
SUBSTRING(t.v, number ,CHARINDEX(',',t.v+',',number)-number)
from
(
select '1,2,3,4,4.5,6' v
union all
select '1.5,2,3,4,4.5,6.6'
)t ,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING(','+t.v,s.number,1) = ','
然后现在需要把 字符串中的小数 过滤掉,就有问题了,会报错:
select *
from
(
select
v,
SUBSTRING(t.v, number ,CHARINDEX(',',t.v+',',number)-number) as vv
from
(
select '1,2,3,4,4.5,6' v
union all
select '1.5,2,3,4,4.5,6.6'
)t ,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING(','+t.v,s.number,1) = ','
)t
where vv not like '%.%'
/*消息 537,级别 16,状态 2,第 3 行
传递给 LEFT 或 SUBSTRING 函数的长度参数无效。*/
在递归 CTE 中使用分析函数可能会出现问题,具体请参考下列连接第k点。不知道是否有用。
http://msdn.microsoft.com/zh-cn/library/ms175972.aspx