简体   繁体   中英

Count occurrences of a character in sql

I am trying to count number of '*' in my string but it gives me wrong count

DECLARE @LongSentence VARCHAR(MAX)
DECLARE @FindSubString VARCHAR(MAX)
SET @LongSentence = 'Pravin Gaonkar: 29 Jan 2013 17:29:22 :  *'
SET @FindSubString = '*'
SELECT LEN(@LongSentence) - LEN(REPLACE(@LongSentence,@FindSubString,''))[Count]

Output

Count
3

Original - 1 But it gives me 3 count

Database SQL SERVER 2008

The problem on your query is that replacing the * on your string makes it end with three trailing spaces, and LEN doesn't count those. So your result is 3. Try using DATALENGTH :

DECLARE @LongSentence VARCHAR(MAX)
DECLARE @FindSubString VARCHAR(MAX)
SET @LongSentence = 'Pravin Gaonkar: 29 Jan 2013 17:29:22 :  *'
SET @FindSubString = '*'

SELECT DATALENGTH(@LongSentence) - 
       DATALENGTH(REPLACE(@LongSentence,@FindSubString,''))[Count]

This is Oracle query. I'm not sure if LEVEL or ROWNUM that can be used instead of LEVEL is available in your version of SQL. But it may still help you:

SELECT count(*) cnt FROM
(
 SELECT DISTINCT(Instr('Pravin Gaonkar: 29 Jan 2013 17:29:22 :  *', '*', LEVEL)) char_pos
   FROM dual
 CONNECT BY LEVEL <= Length('Pravin Gaonkar: 29 Jan 2013 17:29:22 :  *') 
)
WHERE char_pos > 0
/

SQL>

CNT
---
  1

SQL Server 2008 - Querying a Hierarchical Table Using Hierarchy Methods (GetRoot, and GetLevel...) - equivavelt to Oracle hierarchy used in my example: http://msdn.microsoft.com/en-us/library/3b4f7dae-65b5-4d8d-8641-87aba9aa692d(v=sql.100)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM