I want to create a sequence for this varchar to abcd_ver2 in my PL/SQL. It would have been easier if it was a number instead of varchar. In that case, I could do
seq_num := seq_num + 1;But what can I do when I want to change abcd_ver1 to abcd_ver2 (to increment the number in that varchar column by 1)?
Let's do this a brute force way. First, we'll need to find the number in the string, and then we'll need to increment it and add it back to the string. So we'll do this with something similar to the following PL/SQL block:
DECLARE my_string VARCHAR2(50); string_portion VARCHAR2(50); number_portion VARCHAR2(50); the_number NUMBER; string_location NUMBER; BEGIN /* define the string */ my_string := 'abcd_ver2'; /* find where the number is */ /* use the fact that INSTR returns zero */ /* if not found */ string_location:=MIN(DECODE(INSTR(my_string,'0'),0,999,INSTR (my_string,'0')),DECODE(INSTR(my_string,'1'),0,999,INSTR(my_string ('1')),....,DECODE(INSTR(my_string,'9'),0,999,INSTR(my_string,'9'))); /* now that we know where the number is, */ /* get the string and number portions */ string_portion:=SUBSTR(my_string,1,string_location-1); number_portion:=SUBSTR(my_string,string_location); /* Convert the number to NUMBER datatype */ /* and increment it */ the_number:=TO_NUMBER(number_portion); the_number:=the_number+1; /* Place the number back on the string */ my_string := string_portion || TO_CHAR(the_number); END; /The above code can be modified for your specific needs. It relies on the fact that INSTR returns zero if the search is unsuccessful. If a zero is return, we use '999' instead, otherwise, we use the string position. We then return the minimum value of all string positions (or 999) to find the first occurence of a number in the main string. By using SUBSTR, we can pull apart the characters from the number. This lets us then increment the number and then concantenate it back with the characters. Don't forget to finish out the "MIN(DECODE" statement. I put "..." to indicate that you should finish for all numbers.
For More Information
- What do you think about this answer? E-mail the editors at editor@searchDatabase.com with your feedback.
- The Best Oracle Web Links: tips, tutorials, scripts, and more.
- Have an Oracle or SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical Oracle and SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle database design and architecture
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.