35

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?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
aarona
  • 35,986
  • 41
  • 138
  • 186

4 Answers4

28

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;
Tengiz
  • 1,902
  • 14
  • 12
23

This is the SQL equivalent of eval(my_string);:

@Expression = 'SELECT "Hello, World!";';
PREPARE myquery FROM @Expression;
EXECUTE myquery;

Basically I combined the existing answers, neither tells you how to do eval exactly.


If you want to add parameters, you can use this:

@username = "test";
@password = "asdf";
@Expression = 'SELECT id FROM Users WHERE name = ? AND pass = ?;'
PREPARE myquery FROM @Expression;
EXECUTE myquery USING @username, @password;

And to answer the original question exactly:

@Expression = 'SELECT "Hello, World!";'
PREPARE myquery FROM @Expression;
INSERT INTO Results
  EXECUTE myquery;

Note that the PREPARE ... FROM statement wants a session variable (prefixed with @). If you try to pass a normal variable, it will throw its hands up in the air and it just won't care.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Luc
  • 5,339
  • 2
  • 48
  • 48
  • 1
    `@Expression = 'SELECT "Hello, World!";';` doesn't work for me. I'm using MySQL v5.6.30. – kenorb Aug 02 '16 at 10:42
  • @kenorb Strange because I'm certain this worked on a recent mysql version. Might it have something to do with setting a different delimiter? (I might have done that but forgotten that it affected this.) – Luc Aug 02 '16 at 11:08
  • 6
    Maybe `SET` is needed before. – kenorb Aug 02 '16 at 11:11
  • +1 for the rhyme! _it will throw its hands up in the air and it just won't care_ Code works perfectly! – Rahul Chawla Aug 21 '17 at 21:19
19

EXECUTE is a valid command in MySQL. MySQL reference manual

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Brandon Bodnar
  • 8,202
  • 2
  • 36
  • 42
2

The EXECUTE MySQL command can only be used for one prepared statement.

If case you want to execute multiple queries from the string, consider saving them into file and source it, e.g.

SET @query = 'SELECT 1; SELECT 2; SELECT 3;';
SELECT @query INTO OUTFILE '/tmp/temp.sql';
SOURCE /tmp/temp.sql;
kenorb
  • 155,785
  • 88
  • 678
  • 743