用SQL自定義函數(shù)統(tǒng)計(jì)字逗號(hào)分隔符的字符總個(gè)數(shù)
如果SQL數(shù)據(jù)庫(kù)需要統(tǒng)計(jì)某條記錄,某個(gè)字段中用逗號(hào)分開(kāi)后的字符個(gè)數(shù),如某記錄某段的內(nèi)容如下:a,b,c,d,e,f ,g 統(tǒng)計(jì)的結(jié)果應(yīng)該為: 7 ,那么,這個(gè)SQL自定義函數(shù)要如何寫(xiě)呢?下面將為您示例:
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
使用方法:
select dbo.f_count_sub_string('a,b,c,d,e,f,g',',')
結(jié)果為:
7
【編輯推薦】