Number of times a particular character appears in a string

后端 未结 10 2407
终归单人心
终归单人心 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: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)
    

提交回复
热议问题