COUNT a char in a VARCHAR

  • How do I count the frequentie of a char within a varchar?

    "like if we do it for: i" -> 4

  • DECLARE @a VARCHAR(30)

    SET @a = 'like if we do it for: i'+'x'

    SELECT LEN(@a), LEN(REPLACE(@a, 'i', ''))

                           

    ----------- -----------

    24          20

    (1 row(s) affected)

    Caution when there is a space at the end of the REPLACed string. In that case you need to add a dummy string at the end, otherwise you'll get wrong results.

    DECLARE @a VARCHAR(30)

    SET @a = 'like if we do it for: i'

    SELECT LEN(@a), LEN(REPLACE(@a, 'i', ''))

                           

    ----------- -----------

    23          18

    (1 row(s) affected)

     

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • Btw, are you the guy who has developed the Mambo/Joomla Bookmarks component?

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • No I'm not, thx for your solution

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply