SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE function [dbo].[fnQueryCharCountFromString](@str varchar(8000),@sub varchar(50)) returns int as begin declare @pos int,@n int select @n=0, @pos=charindex(@sub,@str) while(@pos<>0) begin select @str=right(@str,len(@str)-@pos),@pos=charindex(@sub,@str),@n=@n+1 end return(@n) end