拆分02
用SQL 自定义函数 统计字逗号“,”分隔符的字符总个数
在工作过程中突然间遇到一个要统计某条记录,某个字段中用逗号分开后的字符个数。
如某记录某段的内容如下:a,b,c,d,e,f ,g 统计的结果应该为: 7 。找了一下sql,并没有找到这个函数,
于是叫同事lucky帮我写了一个(因为我的sql实在太菜了,只会select)。
sql function:
CREATE FUNCTION [dbo].[f_count_sub_string]
(@var varchar(500) ,
@split char(1) )
RETURNS int AS
BEGIN
declare @cur char(1)
declare @i int
select @i = 0
declare @total int
select @total = len(@var)
declare @num int
select @num = 1
while @i<=@total
begin
select @i = @i + 1
select @cur = substring(@var,@i,1)
if @cur = @split
select @num = @num+1
end
return @num
END
(@var varchar(500) ,
@split char(1) )
RETURNS int AS
BEGIN
declare @cur char(1)
declare @i int
select @i = 0
declare @total int
select @total = len(@var)
declare @num int
select @num = 1
while @i<=@total
begin
select @i = @i + 1
select @cur = substring(@var,@i,1)
if @cur = @split
select @num = @num+1
end
return @num
END
使用方法:
select dbo.f_count_sub_string('a,b,c,d,e,f,g',',')
结果为:
7
0
0
(请您对文章做出评价)
发表评论
差了点吧.
教你个技巧,将逗号替换为双逗号,或加其它一个字符,那么替换后的字串长度减去原字串长度就是逗号出现的次数. 而逗号隔开的字符个数也就知道了.
DECLARE @MyStr CHAR(200)
SET @MyStr='a,b,c,d,e'
SELECT LEN(REPLACE(@MyStr,',',',,'))-LEN(@MyStr)
教你个技巧,将逗号替换为双逗号,或加其它一个字符,那么替换后的字串长度减去原字串长度就是逗号出现的次数. 而逗号隔开的字符个数也就知道了.
DECLARE @MyStr CHAR(200)
SET @MyStr='a,b,c,d,e'
SELECT LEN(REPLACE(@MyStr,',',',,'))-LEN(@MyStr)
DECLARE @MyStr CHAR(200)
SET @MyStr='a,b,c,d,e'
SELECT LEN(REPLACE(@MyStr,',',',,'))-LEN(@MyStr)
这个的确是一个不错的办法!
SET @MyStr='a,b,c,d,e'
SELECT LEN(REPLACE(@MyStr,',',',,'))-LEN(@MyStr)
这个的确是一个不错的办法!
有这么一个算法的。
不错
请问如何选出包含“b”的所有记录呢,请赐教。
取b的话理论是一样的。
declare @num int
select @num = 1
while @i<=@total
begin
select @i = @i + 1
select @cur = substring(@var,@i,1)
if @cur = @split
select @num = @num+1
end
return @num
END
把上面的 declare @num int
select @num = 1
改为
declare @num int
select @num = 0
即可.
declare @num int
select @num = 1
while @i<=@total
begin
select @i = @i + 1
select @cur = substring(@var,@i,1)
if @cur = @split
select @num = @num+1
end
return @num
END
把上面的 declare @num int
select @num = 1
改为
declare @num int
select @num = 0
即可.