Number of times a particular character appears in a string

后端 未结 10 2375
终归单人心
终归单人心 2020-11-27 16:41

Is there MS SQL Server function that counts the number of times a particular character appears in a string?

相关标签:
10条回答
  • 2020-11-27 17:04

    try that :

    declare @t nvarchar(max)
    set @t='aaaa'
    
    select len(@t)-len(replace(@t,'a',''))
    
    0 讨论(0)
  • 2020-11-27 17:05

    There's no direct function for this, but you can do it with a replace:

    declare @myvar varchar(20)
    set @myvar = 'Hello World'
    
    select len(@myvar) - len(replace(@myvar,'o',''))
    

    Basically this tells you how many chars were removed, and therefore how many instances of it there were.

    Extra:

    The above can be extended to count the occurences of a multi-char string by dividing by the length of the string being searched for. For example:

    declare @myvar varchar(max), @tocount varchar(20)
    set @myvar = 'Hello World, Hello World'
    set @tocount = 'lo'
    
    select (len(@myvar) - len(replace(@myvar,@tocount,''))) / LEN(@tocount)
    
    0 讨论(0)
  • 2020-11-27 17:07

    You can do that using replace and len.

    Count number of x characters in str:

    len(str) - len(replace(str, 'x', ''))
    
    0 讨论(0)
  • 2020-11-27 17:10

    Use this code, it is working perfectly. I have create a sql function that accept two parameters, the first param is the long string that we want to search into it,and it can accept string length up to 1500 character(of course you can extend it or even change it to text datatype). And the second parameter is the substring that we want to calculate the number of its occurance(its length is up to 200 character, of course you can change it to what your need). and the output is an integer, represent the number of frequency.....enjoy it.


    CREATE FUNCTION [dbo].[GetSubstringCount]
    (
      @InputString nvarchar(1500),
      @SubString NVARCHAR(200)
    )
    RETURNS int
    AS
    BEGIN 
            declare @K int , @StrLen int , @Count int , @SubStrLen int 
            set @SubStrLen = (select len(@SubString))
            set @Count = 0
            Set @k = 1
            set @StrLen =(select len(@InputString))
        While @K <= @StrLen
            Begin
                if ((select substring(@InputString, @K, @SubStrLen)) = @SubString)
                    begin
                        if ((select CHARINDEX(@SubString ,@InputString)) > 0)
                            begin
                            set @Count = @Count +1
                            end
                    end
                                    Set @K=@k+1
            end
            return @Count
    end
    
    0 讨论(0)
提交回复
热议问题