How to count the number of occurrences of a character in an Oracle varchar value?

前端 未结 9 1260
醉梦人生
醉梦人生 2020-12-01 07:35

How can I count number of occurrences of the character - in a varchar2 string?

Example:

select XXX(\'123-345-566\', \'-\') from dual;
--         


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 07:59

    Here you go:

    select length('123-345-566') - length(replace('123-345-566','-',null)) 
    from dual;
    

    Technically, if the string you want to check contains only the character you want to count, the above query will return NULL; the following query will give the correct answer in all cases:

    select coalesce(length('123-345-566') - length(replace('123-345-566','-',null)), length('123-345-566'), 0) 
    from dual;
    

    The final 0 in coalesce catches the case where you're counting in an empty string (i.e. NULL, because length(NULL) = NULL in ORACLE).

提交回复
热议问题