tags:

views:

2072

answers:

3

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 this string.

declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'
+13  A: 

Here you go:

declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'
SELECT LEN(@string) - LEN(REPLACE(@string, 'd', '')) AS D_Count
Mladen Prajdic
Cute, I was thinking of iterating with charindex, I like this much better.
vfilby
I agree with vfilby and can confirm this code works in SQL Server 2005 and 2008.
xsl
I agree too...thx a lot for your help..it did work...thx once again..
I am a MySql user. and definately not a guru. What would be the equiv of D_Count in MySQL?
J.J.
D_Count is just an alias for the column. i don't know how you set that in MySql
Mladen Prajdic
You should also divide by the length of what you're looking for. This script works because 'd' is only one character long. If you were looking for 'as', you'd have to divide the answer by two.
Rob Farley
A: 

Thanks for the solution.

Rock
A: 

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.

Rob Farley
This figures you're querying a table called `someTable` which has a column called `original_string`. And the principle will work in any database, you just need to find the equivalent functions.
Rob Farley