日期:2014-05-17 浏览次数:20597 次
;with cte(id,value) as
(
select 1,'a;b;c'
union all select 2,'a;b'
union all select 3,'cc;dd;33'
)
select id,LEN(value)-LEN(replace(value,';',''))+1 as result
from cte
/*
id result
1 3
2 2
3 3
*/
;with cte(id,value) as
(
select 1,'a;b;c'
union all select 2,'a;b'
union all select 3,'cc;dd;33'
union all select 4,'xx'
union all select 5,''
)
select id,LEN(value)-LEN(replace(value,';',''))+case when LEN(value)>0 then 1 else 0 end as result
from cte
/*
id result
1 3
2 2
3 3
4 1
5 0
*/
declare @t table(id int ,value varchar(100))
insert into @t
select 1,'a;b;c'
union all select 2,'a;b'
union all select 3,'cc;dd;33'
union all select 4,''
select id as 名字,
len(value) - len(replace(value,';','')) as 个数
from @t t
/*
名字 个数
1 2
2 1
3 2
4 0
*/
create table wg
(x int,y varchar(10))
insert into wg
select 1,'a;b;c' union all
select 2,'a;b' union all
select 3,'cc;dd;33'
select a.x '名字',
count(substring(a.y,b.number,charindex(';',a.y+';',b.number)-b.number)) '个数'
from wg a
inner join master.dbo.spt_values b
on b.type='P' and b.number between 1 and len(a.y)
and substring(';'+a.y,b.number,1)=';'
group by a.x
/*
名字 个数
----------- -----------
1 3
2 2
3 3
(3 row(s) affected)
*/