有这样一个需求:
临时表sql:
create table #AA ( ID int, Name nvarchar(20) ) insert #AA select 1,'苏州/上海/温州' union all select 2,'南京' union all select 3,'北京/连云港'
方法:

1 with hh as 2 (select ID, 3 Name=cast(left(Name,charindex('/',Name+'/')-1) as nvarchar(100)), 4 Split=cast(stuff(Name+'/',1,charindex('/',Name+','),'') as nvarchar(100)) 5 from (SELECT ID,Name FROM #AA) t 6 union all 7 select ID, 8 Name=cast(left(Split,charindex('/',Split)-1) as nvarchar(100)), 9 Split= cast(stuff(Split,1,charindex('/',Split),'') as nvarchar(100)) from hh where split>'') 10 11 select ID,Name from hh group by ID,Name
感觉这个查询还是比较复杂的,下面就这个查询中用到的知识点做一个梳理。
1.charindex函数:返回字符或字符串在另一个字符串中开始的位置,如下所示:
如果找不到则返回0,自己可以试一下。
2.left函数
取一个字符串的前若干位,如下:
right函数是同样的道理,只是方向不同。
3.cast方法,转换类型的方法之一,如下:
上面也演示了convert转换的方法。
4 with as的用法,请参看另一个练习示例。
5.stuff方法
学习链接:http://www.cnblogs.com/345563452/archive/2009/10/29/1592048.html
该方法的作用:删除指定长度的字符串,并在指定的起点插入另一组字符。这个方法的参数比较多,有4个,所以看起来比较费劲。如下:
里面的参数有必要说明一下:
2表示删除的起始位置;3表示删除的长度;‘123’表示要插入的字符串。
片段分析:
我的版本:

1 with hhh as 2 ( 3 select ID, 4 Name=cast(left(Name,charindex('/',Name+'/')-1) as nvarchar(100)), 5 Split=SUBSTRING(Name,charindex('/',Name)+1,LEN(Name)-charindex('/',Name)) 6 from (SELECT ID,Name FROM #AA) t 7 union all 8 select ID, 9 Name=cast(left(Split,charindex('/',Split+'/')-1) as nvarchar(100)), 10 Split=(case when charindex('/',Split)>0 then 11 SUBSTRING(Split,charindex('/',Split)+1,LEN(Split)-charindex('/',Split)) 12 else '' end) 13 from hhh where split>'' 14 ) 15 select ID,Name from hhh group by ID,Name