• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 322
  • Last Modified:

Oracle SQL Change Last Character of String

I usually work in MS SQL, but in Oracle, I need to change the last character of a value in a text field in TableA to a '7' if a value in field2 in TableB is '200'.  (Both tables have the acct field.)  Here is my code:

UPDATE (SELECT A.field1, B.field2
               FROM TableA A, TableB B
             WHERE A.acct=B.acct and B.field2 = '200')
        
SET A.field1 = left([field1],len([field1])-1) & '7';

Any help would be greatly appreciated!   THANKS!
Terry
0
SCTCIT
Asked:
SCTCIT
  • 2
  • 2
1 Solution
 
slightwv (䄆 Netminder) Commented:
in 10g and above:
regexp_replace(column_name,'.$','7')

I'll work on the join.
0
 
sdstuberCommented:
this should work in any version

or you can change the SET to use the regexp above

UPDATE tablea
   SET field1  = SUBSTR(field1, 1, LENGTH(field1 - 1)) || '7'
 WHERE acct IN (SELECT acct
                  FROM tableb
                 WHERE field2 = '200')
0
 
sdstuberCommented:
actually, there is a slight difference.


the regexp version will update NULL to be NULL
mine will update NULL to be '7'

both should work for all populated strings though.

if you want to skip NULL's then, rather than modifying the SET,  add that to the WHERE clause

 WHERE acct IN (SELECT acct
                  FROM tableb
                 WHERE field2 = '200')
AND field1 IS NOT NULL
0
 
slightwv (䄆 Netminder) Commented:
sdstuber posted the full update using IN.

Here is what I was going for.  Same rules apply for nulls pointed out by sdstuber.
drop table tab1 purge;
create table tab1(acct number primary key, field1 varchar2(100));

drop table tab2 purge;
create table tab2(acct number primary key, field2 varchar2(100));

insert into tab1 values(1,'abcdef');
insert into tab1 values(2,'abcdef');
insert into tab2 values(2,'200');
commit;



update (select field1 
   from tab1 t1 
   inner join tab2 t2 on t1.acct = t2.acct 
   where t2.field2 = '200') t
   set t.field1=regexp_replace(field1,'.$','7');

select * from tab1;

Open in new window

0
 
SCTCITAuthor Commented:
THIS WORKED!!!  Thanks so much!
Terry
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now