if object_id('[tb]') is not null drop table [tb] go create table [tb]([code] varchar(50),[code2] varchar(50)) insert [tb] select 'a1,a2','a1a1a1a1,a2a2a2a2' union all select 'b1,b2','b1b1b1b1,b2b2b2b2'
go
with cte as ( select [code], SUBSTRING(t.[code2], number ,CHARINDEX(',',t.[code2]+',',number)-number) as code2
from [tb] t,master..spt_values s where s.number >=1 and s.type = 'P' and SUBSTRING(','+t.[code2],s.number,1) = ',' ) ,cte1 as ( 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) = ',' ) select code ,code2, charindex(code,code2)from cte1
--select code ,code2 from cte1 where charindex(code,code2)>0
------解决思路---------------------- 我也有啊。这个帖子我也试过了。一样的。 这个例子 需要对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 ------解决思路---------------------- 你把你的CTE1里面的SELECT 换成* 看看CTE1 你就懂了。为啥这个不能用上面的CHARINDEX。 ------解决思路---------------------- 反复测了一下,并且google了一下,只能说这是编译的过程中顺序并不是你写法那样,即使我再用一个cte包住同样出错,最后如果我把select code ,code2, charindex(code,code2) as c into #t from cte1 然后再 select * from #t where c>0就不抱错了,因为不需要重新计算charindex(code,code2) ------解决思路---------------------- 另外只有charindex(code,code2)=0才报错,=1不抱错 ------解决思路----------------------
反复测了一下,并且google了一下,只能说这是编译的过程中顺序并不是你写法那样,即使我再用一个cte包住同样出错,最后如果我把select code ,code2, charindex(code,code2) as c into #t from cte1 然后再 select * from #t where c>0就不抱错了,因为不需要重新计算charindex(code,code2)
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 '%.%' /*