在开始写之前需要先说下这两个函数的用法,
SubString(str,pos,len): 从pos位置截取字符串STR,len个字符
CHARINDEX ( expression1 ,expression2, [ start_location ] ) :expression1查找的字符,expression2要搜索的字符序列, 需要搜索的其实位置
创建一个表,insert如下数据
create table test
( code varchar(10),
single_No varchar(100))
insert into test(code,single_No)
select '001',',201801001,201801004,201801005,201801006,'
union
select '002',',201801002,201801003,201801009,201801007,201801008,'
;with temp as
( select a.code,a.single_No, charindex(',',a.single_No) as start, charindex(',',a.single_No)-1 as lenth
from test a
union all
select b.code,b.single_No,charindex(',',b.single_No,start+1), charindex(',',b.single_No,start+1)-start-1 as lenth
from temp b
where start<>0
)
select top(100) percent substring(single_No,start -lenth,lenth) as obj, code
into #te
from temp
where (start <> 0)
order by code
转换为多行如下图