Question: How to perform string interpolation is Oracle using PLSQL? Given a template with named parameters enclosed within curly braces then substitute named parameters for variables. Functionality similar to languages like C# string interpolation, Java. The code should be optimised for performance, though mostly will be used infrequently.
The curly braces are mandatory as the templates are business user defined and held in tables. This is a standard convention used in the company. The target is to "mail merge" business documents and snippets in Oracle itself.
Implementation:
Preferably package functions that operate both in PLSQL and SQL. For SQL a csv list of name value pairs will be passed in example 'name, jane, age, 26'
. name, value, name, value
etc...
Example use case:
Note the use of double curly braces as an escape for the literal '{'. The template will be stored in a database table, the substitution variables will be derived at run-time based on complex rules. The example below is just simple:
template = 'Hi my name is {name}, I am aged {age}, yes {age}! Replaced placeholders {{name}}, {{age}}'
variables = name: jane, age: 26
output = Hi my name is Jane, I am aged 26, yes 26! Replaced placeholders {name} and {age}
Example PLSQL with call to imaginary package:
DECLARE v_template NVARCHAR2(500);
v_name NVARCHAR2(50) := 'Jane';
v_age NVARCHAR2(50) := '26';
v_output NVARCHAR2(1000); TYPE ty_dictionary IS TABLE OF NVARCHAR2(1000) INDEX BY VARCHAR2(200);
v_vars ty_dictionary;
BEGIN
-- note, escaped double curly braces {{ will output {,
v_template := 'Hi my name is {name}, I am aged {age}, yes {age}! Replaced placeholders {{name}}, {{age}}';
v_vars('name') := v_name;
v_vars('age') := v_age;
v_output:= pkg_interpolation.fn_format(v_template, v_vars);
-- should output:
-- Hi my name is Jane, I am aged 26, yes 26! Replaced placeholders {name} and {age}
dbms_output.put_line('output: ' || v_output);
END;