Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute a string in MySQL?

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?

like image 733
aarona Avatar asked Jun 16 '09 01:06

aarona


People also ask

Can we use string in MySQL?

The string data types are CHAR , VARCHAR , BINARY , VARBINARY , BLOB , TEXT , ENUM , and SET . In some cases, MySQL may change a string column to a type different from that given in a CREATE TABLE or ALTER TABLE statement.

What is string function in MySQL?

Inserts a string within a string at the specified position and for a certain number of characters. INSTR. Returns the position of the first occurrence of a string in another string. LCASE. Converts a string to lower-case.


2 Answers

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;
like image 103
Tengiz Avatar answered Oct 16 '22 16:10

Tengiz


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.

like image 22
Luc Avatar answered Oct 16 '22 15:10

Luc