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 > how to select substring after

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 12-08-10, 16:13
mlybarger mlybarger is offline
Registered User
 
Join Date: Dec 2010
Posts: 8
how to select substring before

i have data such as:

A
----

A Data, More Data
B Data, More Data
C Data, More, Data
D Data & More, Data
E Data
F More
G Data, Data

I'm trying to get the data selected as "everything before the first coma, or the first ampersand so the results would be:

A
-----------
A Data
B Data
C Data
D Data
E Data
F More
G Data

I try to use substr(A,1,posstr(',',A)-1), but that doesn't seem to work so nicely where there's no coma.

Any help would be most appreciated.

thanks!

Last edited by mlybarger; 12-08-10 at 17:58. Reason: error
Reply With Quote
  #2 (permalink)  
Old 12-08-10, 18:22
Lenny77 Lenny77 is offline
Registered User
 
Join Date: Jul 2009
Location: NY
Posts: 886
Lightbulb

Try to use something like this:

Code:
select t1.A, left(t1.A, t2.posA)
from 
(select 'A abcd, efg%%%%%' A
   from sysibm.sysdummy1) t1
join table
(select t1.A, 
case when locate(',', t1.A) < 1 then length(t1.A) 
     else locate(',', t1.A) - 1  end posA
   from sysibm.sysdummy1) t2
on t1.A = t2.A
Compare result to:

Code:
select t1.A, left(t1.A, t2.posA)
from 
(select 'A abcdefg%%%%%' A
   from sysibm.sysdummy1) t1
join table
(select t1.A, 
case when locate(',', t1.A) < 1 then length(t1.A) 
     else locate(',', t1.A) - 1  end posA
   from sysibm.sysdummy1) t2
on t1.A = t2.A
Lenny
Reply With Quote
  #3 (permalink)  
Old 12-10-10, 16:09
yvanroy yvanroy is offline
Registered User
 
Join Date: Jun 2002
Posts: 12
how to select substring before

or maybe something like this:

Code:
with
 sample as
  (select 'A abcd& efg%%%%%' as A
   from sysibm.sysdummy1
  )
select
left(sample.a,min(coalesce(nullif(locate(',', sample.A)-1,-1),length(sample.a))
                 ,coalesce(nullif(locate('&', sample.A)-1,-1),length(sample.a))
                 ,length(sample.a)
                 )
    )
from sample
;
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