If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > DB2 > DB2 String function

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 09-23-11, 05:08
kayal kayal is offline
Registered User
 
Join Date: Sep 2011
Posts: 8
DB2 String function

Hi,

I want to get the function to count the number of occurance of a particular character in a string.
Ex. In the string 'xx, yy, zz', I want to get the number of ','s(Commas).

Thanks,
Kayal
Reply With Quote
  #2 (permalink)  
Old 09-23-11, 05:24
dbzTHEdinosaur dbzTHEdinosaur is offline
Registered User
 
Join Date: Jun 2007
Location: germany
Posts: 96
= length(string) - length(replace(string,','.''))
__________________
Dick Brenholtz, Ami in Deutschland
Reply With Quote
  #3 (permalink)  
Old 09-23-11, 05:27
tonkuma tonkuma is offline
Registered User
 
Join Date: Feb 2008
Location: Japan
Posts: 2,193
Try
( LENGTH('xx, yy, zz') - LENGTH( REPLACE('xx, yy, zz' , ',' , '') ) ) / LENGTH(',')

Sorry,
Dick is right.

I forgot OP wrote "a particular character", not "a particular string".
So "/ LENGTH(',')" is not necessary.

Last edited by tonkuma; 09-23-11 at 05:32. Reason: Add notes "Sorry, Dick is right. I forgot ...."
Reply With Quote
  #4 (permalink)  
Old 09-23-11, 08:12
n_i n_i is offline
:-)
 
Join Date: Jun 2003
Location: Toronto, Canada
Posts: 4,449
Actually, a particular character could be more than 1 byte long in a Unicode database, while LENGTH() returns the number of bytes, so I would use Tonkuma's suggestion to be on the safe side.
Reply With Quote
  #5 (permalink)  
Old 09-23-11, 09:09
dbzTHEdinosaur dbzTHEdinosaur is offline
Registered User
 
Join Date: Jun 2007
Location: germany
Posts: 96
Quote:
Originally Posted by n_i View Post
Actually, a particular character could be more than 1 byte long in a Unicode database, while LENGTH() returns the number of bytes, so I would use Tonkuma's suggestion to be on the safe side.
we are looking for occurances,
so good point and accurate.

being from an ebcdic only, mainframe environment, I forget that there are other worlds out there.
__________________
Dick Brenholtz, Ami in Deutschland
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On