如何计算 Oracle varchar 值中某个字符出现的次数? [英] How to count the number of occurrences of a character in an Oracle varchar value?

查看:46
本文介绍了如何计算 Oracle varchar 值中某个字符出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算 varchar2 字符串中字符 - 的出现次数?

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

示例:

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

推荐答案

给你:

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

从技术上讲,如果你要检查的字符串只包含你要计数的字符,上面的查询将返回NULL;以下查询将在所有情况下给出正确答案:

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;

coalesce 中的最后一个 0 捕捉您在空字符串中计数的情况(即 NULL,因为在 ORACLE 中 length(NULL) = NULL).

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).

这篇关于如何计算 Oracle varchar 值中某个字符出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆