saeid Arianpour
saeid Arianpour

Reputation: 59

evaluate expression in MySQL

I have a table with column a,b, expr that expr is an expression from other column. for example table contains

a   b   expr
------------
2   5   a+b
3   4   a*b+3

I like simply run a query and get flowing result:

a | b | expr 
------------ 
2 | 5 | 7 
3 | 4 | 15

I search doc for function, procedure etc, but i can't do it. please help me!

Upvotes: 4

Views: 7854

Answers (2)

fancyPants
fancyPants

Reputation: 51888

Here is a solution I made for fun. Consider solving this with a real programming language, if this is not a one time thing to do.

drop table if exists Table1;
CREATE TABLE Table1
    (`a` int, `b` int, `expr` varchar(6))
;

INSERT INTO Table1
    (`a`, `b`, `expr`)
VALUES
    (2, 5, 'a+b'),
    (3, 4, 'a*b +3')
;

drop table if exists Table2;
CREATE TABLE Table2
    (`a` int, `b` int, `expr` int)
;

drop procedure if exists curdemo;
DELIMITER $$
CREATE PROCEDURE curdemo()
BEGIN
  DECLARE done INT DEFAULT 0;
  DECLARE seqel VARCHAR(255);
  DECLARE cur1 CURSOR FOR SELECT CONCAT('INSERT INTO Table2 (a, b, expr) SELECT a, b, ' , expr, ' FROM (SELECT ', a, ' as a, ', b, ' as b) sq;') FROM Table1;
  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO seqel;
    IF NOT done THEN
       SET @sql:=seqel;
       PREPARE stmt FROM @sql;
       EXECUTE stmt;
       DEALLOCATE PREPARE stmt;
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;
END $$
DELIMITER ;

CALL curdemo();

SELECT * FROM Table2;

Upvotes: 2

mee
mee

Reputation: 332

If i understood your question correctly, this is what you are looking for:

SELECT a, b, (a+b) AS expr FROM yourtable;

Upvotes: -1

Related Questions