带有informix的Eval数学表达式字符串

时间:2016-06-16 06:05:09

标签: sql expression eval informix

我需要从字符串中计算数学表达式。

字符串看起来像" 1.00 * 1.00 * 4.00"

我该怎么做?

这样的东西
Select field1, field2, EVAL("EXPRESSION") as float from table

会很棒!

1 个答案:

答案 0 :(得分:4)

让我们创建一个测试用例:

CREATE TABLE tab1(
    col1 DECIMAL(10,2),
    col2 DECIMAL(10,2),
    col3 DECIMAL(10,2),
    col4 VARCHAR(250)
);

INSERT INTO tab1 VALUES (1.0, 1.0, 4.0, "1.00*1.00*4.00")

如果要从列构建表达式甚至传递字符串,那么它很简单:

SELECT  col1 * col2 * col3  AS from_field,
        1.00*1.00*4.00      AS from_string
FROM    tab1;

如果值存储在列中,则必须以编程方式执行,以下是SPL的示例:

CREATE FUNCTION get_eval()
    RETURNING DECIMAL(10,2) AS eval;

    DEFINE stmt     VARCHAR(250);
    DEFINE eval_str VARCHAR(250);
    DEFINE eval_dec DECIMAL(10,2);

    FOREACH cur FOR 
        SELECT  col4
        INTO    eval_str
        FROM    tab1 

        LET stmt = "SELECT " || eval_str || " as eval FROM sysmaster:sysdual INTO TEMP tmp_eval WITH NO LOG;";
        EXECUTE IMMEDIATE stmt;

    END FOREACH

    FOREACH eval FOR
        SELECT  eval
        INTO    eval_dec
        FROM    tmp_eval
            RETURN eval_dec WITH RESUME;
    END FOREACH

    DROP TABLE tmp_eval;

END FUNCTION;

EXECUTE FUNCTION get_eval();