评估数学表达式

时间:2014-02-22 15:00:38

标签: mysql sql

我的列类型为varchar,此列的值是数学运算(只是加法和减号运算)

col
------
2+3+2+1
3+3-4
1+1-2.5

有可能,评估这个表达式吗?需要的结果是:

col
---------- 
8
2
-0.5

1 个答案:

答案 0 :(得分:4)

由于您无法在EXECUTE IMMEDIATE中使用CREATE FUNCTION或准备好的语句(这有助于使用简单CONCAT("SELECT ", expr, " FROM dual")评估表达式),请参阅下面的一个使用的解决方案实际计算数学表达式的函数的一个函数(因为您的问题只涉及+-运算符的简单表达式)

DELIMITER $$

CREATE FUNCTION calc(expr VARCHAR(255)) RETURNS FLOAT
BEGIN
  DECLARE result FLOAT;
  DECLARE operand VARCHAR(255);
  DECLARE operator INT;
  DECLARE i INT;
  DECLARE c CHAR;

  SET i = 1;
  SET result = 0;
  SET operand = 0;
  SET operator = 1;

  WHILE(i <= LENGTH(expr)) DO
    SET c = SUBSTR(expr, i, 1);

    IF c = '+' THEN
        SET result = result + operator * operand;
        SET operator = 1;
        SET operand = '';
    ELSEIF c = '-' THEN
        SET result = result + operator * operand;
        SET operator = -1;
        SET operand = '';
    ELSE
        SET operand = CONCAT(operand, c);
    END IF;

    SET i = i + 1;
  END WHILE;

  SET result = result + operator * operand;

  RETURN result;
END$$

创建此功能后,您只需使用SELECT命令:

SELECT calc(col) FROM tbl;

Here's the DEMO.