Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to evaluate an arbitrary expression in PL/SQL

650745Feb 23 2009 — edited Feb 27 2009
Hi there,

Can anyone tell me whether it is possible to evaluate an arbitrary expression dynamically in PL/SQL.
I am using Oracle9i Enterprise Edition Release 9.2.0.6.0.

I would like to be able to do something like:
DECLARE
    MyVar                        VARCHAR2(9);
    MyExpression                 VARCHAR2(99);
    MyResult                     BOOLEAN := FALSE;
BEGIN
    MyVar                        := 'Yes';
    MyExpression                 := 'MyVar = ''Yes''';
    IF MyExpression                                                -- <== this does not work: PLS-00382: expression is of wrong type
    THEN
        MyResult := TRUE;
    END IF;
    IF MyResult
    THEN
        DBMS_OUTPUT.PUT_LINE(MyExpression||' is true');
    ELSE
        DBMS_OUTPUT.PUT_LINE(MyExpression||' is false');
    END IF;
END;
/
One way I tried to solve my problem is using dynamic SQL, but I do not think this is the answer.
For instance:
DECLARE
    MyVar                        VARCHAR2(9);
    MyExpression                 VARCHAR2(99);
    MySQLStatement               VARCHAR2(999);
    MyResultString               VARCHAR2(5) := 'FALSE';
    MyResult                     BOOLEAN := FALSE;
BEGIN
    MyVar          := 'Yes';
    MyExpression   := ':MyVar = ''Yes''';
    MySQLStatement := 'SELECT ''TRUE'' FROM DUAL WHERE '||MyExpression;
    BEGIN
        EXECUTE IMMEDIATE MySQLStatement INTO MyResultString USING MyVar;
    EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
        MyResultString := 'FALSE';
    END;
    MyResult := MyResultString = 'TRUE';
    IF MyResult
    THEN
        DBMS_OUTPUT.PUT_LINE(MyExpression||' is true');
    ELSE
        DBMS_OUTPUT.PUT_LINE(MyExpression||' is false');
    END IF;
END;
/
The problem with this approach is that the USING clause must refer to a specific variable.

Anyone has a bright idea?

Thanks, Jaap
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 27 2009
Added on Feb 23 2009
21 comments
1,415 views