In our Oracle database we have a table called RULES, with a field called SQLQUERY. This field is a varchar with an SQL statement stored. The PK is DM_PROJECT.
A typical statement that is stored could be
select ACCOUNTNUMBER from CUSTOMERS where ACCUMULATED_SALES > 500000
I want to do something like this:
select
*
from
customers
where
accountnumber like 'A%'
or salesregion = 999
or accountnumber in
(
<run the query SQLQUERY from RULES where DM_PROJECT=:DM_PROJECT>
)
Can this be done?
(Secondary concern: Can it be done if the stored query uses its own variables, like
select ACCOUNTNUMBER from CUSTOMERS where ACCUMULATEDSALES > :LIMIT
)
Interesting question indeed. There are two aspects to this.
The first is whether it’s a good idea. The problem is, the text in the RULE is invisible to the database. It won’t show up in dependency checks, so impact analysis becomes hard. Obviously (or maybe not obviously) the syntax of the Rule can only be verified by running it. This can create problems with adding rules. So it can also be a maintenance problem. And, as we shall see, once you move beyond simplistic queries it is tough to program with.
The second aspect is whether it’s possible. It is. We need to use dynamic SQL; combining dynamic SQL with static SQL is doable but gnarly.
This function gets a rule, executes it and returns a numeric array.
Let’s test it.
Which is the one and only correct answer.
But now we come to your suplementary question:
Yes it can, but things start to get a bit more brittle. New rule:
We amend the function to apply it:
Fingers crossed!
Okay, so it still works. But you can see that the permutations are not friendly. If you want to pass more than one argument to the RULE then you need more functions or a twistier internal logic. If you want to return sets of dates or strings you need more functions. If you want to pass P_VARIABLE parameters of different data_types you may need more functions. You certainly need some type checking pre-conditions.
Which comes back to my first point: yes it can be done, but is it worth the hassle?