Click here to Skip to main content
15,881,803 members
Articles / Programming Languages / SQL
Alternative
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
15 Aug 2011CPOL 10.7K   3
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)


Written By
Software Developer (Senior)
New Zealand New Zealand
I've spent time programming for the security industry, video games, and telephony. I live in New Zealand, and have a Bachelor of Computing and Mathematical Sciences specializing in Computer Technology, from the University of Waikato in Hamilton, New Zealand.

Comments and Discussions

 
GeneralI would add this at the start: if @Input is null or @Search... Pin
Chris Maunder15-Aug-11 5:37
cofounderChris Maunder15-Aug-11 5:37 
GeneralReason for my vote of 5 I love it. Pin
dmjm-h19-Jul-11 3:08
dmjm-h19-Jul-11 3:08 
GeneralThat's solution I wanted to post :) with some added check up... Pin
cerda6-Jul-11 19:46
cerda6-Jul-11 19:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.