How to loop over tokens from a string in oracle?

by giovanny.lueilwitz , in category: MySQL , a day ago

How to loop over tokens from a string in oracle?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 3 hours ago

@giovanny.lueilwitz 

In Oracle PL/SQL, you can loop over tokens from a string by using the REGEXP_SUBSTR function along with a loop. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
DECLARE
   my_string VARCHAR2(100) := 'Hello|World|Oracle|PL/SQL';
   delimiter VARCHAR2(1) := '|';
   token VARCHAR2(100);
   pos NUMBER := 1;
BEGIN
   LOOP
      token := REGEXP_SUBSTR(my_string, '[^'||delimiter||']+', 1, pos);
      EXIT WHEN token IS NULL;
      
      DBMS_OUTPUT.PUT_LINE(token);
      
      pos := pos + 1;
   END LOOP;
END;


In this example, we have a string my_string that contains tokens separated by a delimiter '|'. We use the REGEXP_SUBSTR function to extract each token from the string and then loop over the tokens using a LOOP construct. The loop exits when there are no more tokens left in the string.


You can modify the delimiter and the regular expression pattern inside the REGEXP_SUBSTR function to suit your specific requirements for tokenizing the string.