2014-02-22 248 views
2

我有柱哪種類型varchar,(和公正的除了減運算)此列的值是數學運算評估數學表達式

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

有可能的是,這evalute表情?所需要的結果是:

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

回答

3

因爲你不能使用CREATE FUNCTIONEXECUTE IMMEDIATE或準備語句(這將在評估一個簡單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.