Is it possible to execute a string in MySQL?

aarona picture aarona · Jun 16, 2009 · Viewed 65.9k times · Source

I have to convert a MSSQL stored proc that passes a varchar that is a query:

INSERT INTO Results
  EXEC (@Expresion);

This isn't working. I'm pretty sure that EXEC and EXECUTE aren't MySQL commands, but CALL doesn't work either.

Does anyone know if it's even possible to have something like JavaScript's eval function for MySQL?

Answer

Tengiz picture Tengiz · Oct 30, 2015

I think you're looking for something like this:

SET @queryString = (
SELECT CONCAT('INSERT INTO user_group (`group_id`,`user_id`) VALUES ', www.vals) as res FROM (
    SELECT GROUP_CONCAT(qwe.asd SEPARATOR ',') as vals FROM ( 
           SELECT CONCAT('(59,', user_id, ')') as asd FROM access WHERE residency = 9 
    ) as qwe 
) as www
);

PREPARE stmt FROM @queryString;
EXECUTE stmt;
DEALLOCATE PREPARE stmt; 
SET @asd = NULL;