Number of times a particular character appears in a string

后端 未结 10 2374
终归单人心
终归单人心 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 16:44

    BEST

    DECLARE @yourSpecialMark = '/';
    select len(@yourString) - len(replace(@yourString,@yourSpecialMark,''))
    

    It will count, how many times occours the special mark '/'

    0 讨论(0)
  • 2020-11-27 16:46

    Use this function begining from SQL SERVER 2016

    Select Count(value) From STRING_SPLIT('AAA AAA AAA',' ');
    
    -- Output : 3 
    

    When This function used with count function it gives you how many character exists in string

    0 讨论(0)
  • 2020-11-27 16:46

    You may do this completely in-line by replacing the desired character with an empty string, calling LENGTH function and substracting from the original string's length.

    SELECT 
      CustomerName, 
      LENGTH(CustomerName) -
      LENGTH(REPLACE(CustomerName, ' ', '')) AS NumberOfSpaces
    FROM Customers;
    
    0 讨论(0)
  • 2020-11-27 16:56

    function for sql server:

    CREATE function NTSGetCinC(@Cadena nvarchar(4000), @UnChar nvarchar(100)) 
    Returns int 
    
     as  
    
     begin 
    
     declare @t1 int 
    
     declare @t2 int 
    
     declare @t3 int 
    
     set @t1 = len(@Cadena) 
    
     set @t2 = len(replace(@Cadena,@UnChar,'')) 
    
     set @t3 = len(@UnChar) 
    
    
     return (@t1 - @t2)  / @t3 
    
     end 
    

    Code for visual basic and others:

    Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long
    
    NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)
    
    End Function
    
    0 讨论(0)
  • 2020-11-27 16:58

    Look at the length of the string after replacing the sequence

    declare @s varchar(10) = 'aabaacaa'
    select len(@s) - len(replace(@s, 'a', ''))
    >>6
    
    0 讨论(0)
  • 2020-11-27 16:58

    You can do it inline, but you have to be careful with spaces in the column data. Better to use datalength()

    SELECT 
      ColName, 
      DATALENGTH(ColName) -
      DATALENGTH(REPLACE(Col, 'A', '')) AS NumberOfLetterA
    FROM ColName;
    

    -OR- Do the replace with 2 characters

    SELECT 
      ColName, 
      -LEN(ColName)
      +LEN(REPLACE(Col, 'A', '><')) AS NumberOfLetterA
    FROM ColName;
    
    0 讨论(0)
提交回复
热议问题