---
title: "ORACLE计算字符在字符串中出现的次数 "
author: "beee"
date: "2013-10-21T19:49:09Z"
tags: []
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2013-10-21T19:49:09Z"
id: 1961900
url: "https://beee.iteye.com/blog/1961900"
---

ORACLE计算字符在字符串中出现的次数

 

SQL&gt; create table t1(describe varchar2(20));

Table created.

SQL&gt; insert into t1 values('hello world');

1 row created.

SQL&gt; insert into t1 values('hello everyone');

1 row created.

SQL&gt; insert into t1 values('hello all');

1 row created.

SQL&gt; commit;

Commit complete.

SQL&gt; select * from t1;

DESCRIBE  
\--------------------  
hello world  
hello everyone  
hello all

SQL&gt; select  
  2  (length(describe)-length(replace(describe,'h','')))/length('h') as cnt  
  3  from t1;

       CNT  
\----------  
         1  
         1  
         1

SQL&gt; select  
  2  (length(describe)-length(replace(describe,'l','')))/length('l') as cnt  
  3  from t1;

       CNT  
\----------  
         3  
         2  
         4

也许你会觉得后面那个除数length()函数是没有用的，的确，在这个例子中是没用的，不过当被查找的字符串长度不为1时，我们再来看看会有什么结果。

SQL&gt; insert into t1 values('hohohoh');

1 row created.

SQL&gt; select  
  2  (length(describe)-length(replace(describe,'ho','')))/length('ho') as cnt  
  3  from t1;

       CNT  
\----------  
         0  
         0  
         0  
         3

SQL&gt; select  
  2  length(describe)-length(replace(describe,'ho','')) as cnt  
  3  from t1;

       CNT  
\----------  
         0  
         0  
         0  
         6       --这个结果是错误的 因为没有除以被查找字符串的长度

SQL&gt;