How can you find the number of occurrences of a particular character in a string using sql?

前端 未结 3 1140
遇见更好的自我
遇见更好的自我 2020-12-05 23:50

How can you find the number of occurrences of a particular character in a string using sql?

Example: I want to find the number of times the letter ‘d’ appears in thi

相关标签:
3条回答
  • 2020-12-06 00:23

    For all you Sybase ASE 15 dinosaurs our there, you will need to replace '' with null, i.e.

    SELECT LEN(@string) - LEN(REPLACE(@string, 'd', null)) AS D_Count
    
    0 讨论(0)
  • If you want to make it a little more general, you should divide by the length of the thing you're looking for. Like this:

    declare @searchstring varchar(10);
    set @searchstring = 'Rob';
    
    select original_string, 
    (len(orginal_string) - len(replace(original_string, @searchstring, '')) 
       / len(@searchstring)
    from someTable;
    

    This is because each time you find 'Rob', you remove three characters. So when you remove six characters, you've found 'Rob' twice.

    0 讨论(0)
  • 2020-12-06 00:31

    Here you go:

    declare @string varchar(100)
    select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'
    SELECT LEN(@string) - LEN(REPLACE(@string, 'd', '')) AS D_Count
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题