Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

Counting the number of occurrences of one string inside another in SQL

5.00/5 (2 votes)
15 Aug 2011CPOL 11.6K  
CREATE FUNCTION [dbo].[com_CountString](@Input nVarChar(max), @SearchString nVarChar(1000))RETURNS INTBEGIN if @Input is null or @SearchString is null return 0 DECLARE @InputLength INT, @SearchLength INT SELECT...
SQL
CREATE FUNCTION [dbo].[com_CountString](@Input nVarChar(max), 
                                        @SearchString nVarChar(1000))
RETURNS INT
BEGIN

    if @Input is null or @SearchString is null
        return 0

    DECLARE @InputLength INT, @SearchLength INT
    SELECT @InputLength  = LEN(@Input), @SearchLength = LEN(@SearchString)

    IF @InputLength = 0 or @SearchLength = 0 or @SearchLength > @InputLength
        return 0

   RETURN (LEN(@input) - LEN(REPLACE(@input, @SearchString, ''))) / LEN(@SearchString)
END

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)