Skip to content
Advertisement

PL/SQL Replacing characters in a string using another table

I need to create function that replaces characters in a string to characters from another table. What I’m trying returns exactly the same string from the beginning. Table t_symbols is:

I need to use cursor and take characters from this table and not just nesting multiple REPLACE

Advertisement

Answer

SQL has a function exactly for this. It is not REPLACE (where indeed you would need multiple iterations); it’s the TRANSLATE function.

If the table contents may change, and you need to write a function that looks things up in the table at the time it is called, you could do something like the function I show below.

I am showing a complete example: First I create a table that will store the required substitutions. I only include the first few substitutions, because I want to show how the behavior of the function changes as the table is being modified – without needing to change anything about the function. (Which is the whole point of this.)

Then I show the function definition, and I demonstrate how it works. Then I insert two more rows in the substitutions table and I run exactly the same query; the result will now reflect the longer “list” of substitutions, as needed.

OK, so now let’s insert a couple more rows into the table and run the same query. Notice how now the g is also substituted for.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement