Number of times a particular character appears in a string

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

提交回复
热议问题