Question

I have a WARNINGS_INFO table that contains some info on a specific warning message, such as it's code and level, and a string that describes how to print the output message.

  ID  |     CODE       | LEVEL | STR_FORMAT
------|----------------|-------|----------------------------------------------
  5   | attrib_missing |   3   | On cell $R:$C, attribute $ATTRIB not found

Let's assume I have a table GENERATED_WARNINGS with all the warnings generated from a SQL batch:

  WARN_ID  |  WARN_ROW_ID   
-----------|---------------
    5      |      32      

Also, I have another table with the columns R, C and ATTRIB and obviously a ROW_ID primary key column which WARN_ROW_ID refers to.

Is there a way in SQL to dynamically trasduce the STR_FORMAT string to a string with the data from the columns of the last table?

Was it helpful?

Solution

Here's one stab at it using the Oracle REPLACE() function: http://www.sqlfiddle.com/#!4/7d3c4/3

This requires a nested call to REPLACE for each $variable in your warning message, so isn't general purpose. For this kind of thing I do not think you should do the variable replacement in SQL. Extract the warning message, and the values for $R, $C, $ATTRIB, etc and do the variable substitution using a templating library like Velocity or FreeMarker.

Given DDL:

create table WARNINGS_INFO (
  ID INTEGER PRIMARY KEY,
  C_CODE VARCHAR2(20),
  I_LEVEL INTEGER,
  STR_FORMAT VARCHAR2(255)
);

insert into WARNINGS_INFO values (
  5, 'attrib_missing', 3, 'On cell $R:$C attribute $ATTRIB not found'
);

create table GENERATED_WARNINGS (
  WARN_ID INTEGER NOT NULL,
  WARN_ROW_ID INTEGER
);

insert into GENERATED_WARNINGS values (5, 32);

create table WARNING_MAP (
  ROW_ID INTEGER PRIMARY KEY,
  R INTEGER,
  C INTEGER,
  ATTRIB VARCHAR2(20)
);

insert into WARNING_MAP values (32, 42, 99, 'FOOBAR');

The following query will do the parameter replacement:

select
  replace(
    replace(
      replace(str_format, '$R', wm.r),
      '$C', wm.c),
    '$ATTRIB', wm.attrib) as formatted
from warnings_info wi
join generated_warnings gw on wi.id = gw.warn_id
join warning_map wm on wm.row_id = gw.warn_row_id
;

The output from this will be: "On cell 42:99 attribute FOOBAR not found"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top