문제

I have a table like give bellow (table name IDN_CONSUMERS),

| USER_ID | USERNAME  |
| 001A    | ABC/Anne  |
| 034K    | ABC/John  |
| DF23    | ABC/Peter |

I need to remove the ABC/ part of the all username and put the modified value back to the table, so the final result should be like,

| USER_ID | USERNAME |
| 001A    | Anne     |
| 034K    | John     |
| DF23    | Peter    |

I tried the following script, but it's not working for a reason I don't understand. Can anyone please help me with this ?

DECLARE 
NEWUSERNAME VARCHAR2(512);

BEGIN

FOR ID IN (SELECT USER_ID FROM IDN_CONSUMERS) LOOP

SELECT SUBSTR((SELECT USERNAME FROM IDN_CONSUMERS WHERE USER_ID='||ID||'), 4) INTO NEWUSERNAME FROM DUAL;

UPDATE IDN_CONSUMERS SET USERNAME='||NEWUSERNAME||' WHERE USER_ID='||ID||';

END LOOP;

END;
도움이 되었습니까?

해결책

There's no need to write a loop or to store the new user name value separately.

UPDATE IDN_CONSUMERS SET USERNAME = SUBSTR(USERNAME, 4);

다른 팁

A more general solution, using REGEXP_REPLACE:

UPDATE idn_consumers
   SET username = REGEXP_REPLACE(username, '.*/');

This does assume there will be only one '/' character in the username field. It does not assume the string to be removed will always be 4 characters long, or that they are all the same length.

If your data can include more than one '/', you can use:

UPDATE idn_consumers
   SET username = REGEXP_REPLACE(username, '[^/]*/','',1,1);

For example:

SQL> SELECT REGEXP_REPLACE('ABC/An/ne', '[^/]*/','',1,1) new_name FROM dual;

NEW_NAME
--------
An/ne
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top