T-SQL function to get a char count
11/18/2008I needed an efficient and reusable way to get character counts in strings at the database level and produced the following udf which takes a string and a character and returns the number of occurrences of the character in the string.
CREATE FUNCTION [dbo].[uf_charCount] (@string varchar(8000), @character char(1))
RETURNS SMALLINT
/*
Purpose: returns the number of occurrences of @character in @string
Author: Kevin J. Miller (www.websolete.com)
Example:
SELECT dbo.uf_charCount('four score and seven years ago','s')
would return: 3
*/
AS
BEGIN
DECLARE @stringtrunc varchar(8000);
SET @stringtrunc = REPLACE(@string,@character,''); -- remove the specified character
RETURN (LEN(@string) - LEN(@stringtrunc)); -- return the difference in length, this is the char count
END
1 comment(s)
Posted by Kevin J. Miller in:SQL Server1 Comments
shima wrote on 06/20/11 2:47 AM
thank you very much.really good idea