如何评估MYSQL表的varchar列中的公式

时间:2013-05-30 08:51:16

标签: mysql

请参阅以下SQL。我们需要在表格中保存STD公式,但无法对此进行评估。

    DROP TEMPORARY TABLE IF EXISTS _std ;
CREATE TEMPORARY TABLE _std(stdformula VARCHAR(4000), mu DECIMAL(18,9), newValue DECIMAL(18,9));

INSERT INTO _std VALUES('SQRT((POWER((5-mu), 2) + POWER((6-mu), 2)  + POWER((7-mu), 2) + POWER((7-mu), 2) )/4)',5+6+7+7/4,7);

SET @temp=(SELECT REPLACE(stdformula,'mu',mu) FROM _std );
SELECT @temp;
-- @temp=> SQRT(( POWER((5-19.750000000), 2) + POWER((6-19.750000000), 2)  + POWER((7-19.750000000), 2) + POWER((7-19.750000000), 2) )/2);
-- which is valid statement
SELECT SQRT(( POWER((5-19.750000000), 2) + POWER((6-19.750000000), 2)  + POWER((7-19.750000000), 2) + POWER((7-19.750000000), 2) )/2);

- 我们如何使用动态SQL方法评估@temp? - 以下准备工作无效

PREPARE StmtStd FROM @temp;
EXECUTE StmtStd; 
DEALLOCATE PREPARE Stmtstd;*

1 个答案:

答案 0 :(得分:0)

SELECT中您遗失了@temp。尝试

...
SET @temp= CONCAT('SELECT ', (SELECT REPLACE(stdformula,'mu',mu) FROM _std ), ' result');
-- SELECT @temp;    
PREPARE StmtStd FROM @temp;
EXECUTE StmtStd;

输出:

|          RESULT |
-------------------
| 13.525438994724 |

这是 SQLFiddle 演示