Home Forums SQL Server 2008 T-SQL (SS2K8) tsql query - Count the number of spaces in a string RE: tsql query - Count the number of spaces in a string

  • Very nice. I needed some code to find the number of occurrences of more than one character and I found that all I had to do was add a divisor.

    CREATE FUNCTION [dbo].[fn_NumOccurrences]

    (

    @sourceString varchar(1000)

    , @searchString varchar(10)

    )

    RETURNS INTEGER

    AS

    BEGIN

    DECLARE @numTimes INTEGER = 0

    SELECT @numTimes = (DATALENGTH(@sourceString) - DATALENGTH(REPLACE(@sourceString COLLATE Latin1_General_BIN2, @searchString, ''))) / DATALENGTH(@searchString);

    RETURN @numTimes

    END