Home > Database > Mysql Tutorial > Can MySQL Execute a String as a Query Like JavaScript\'s eval()?

Can MySQL Execute a String as a Query Like JavaScript\'s eval()?

Mary-Kate Olsen
Release: 2024-11-29 09:35:16
Original
364 people have browsed it

Can MySQL Execute a String as a Query Like JavaScript's eval()?

Can MySQL Execute a String as a Query?

Question:

In a MySQL environment, attempting to execute a stored procedure that passes in a varchar as a query via EXEC or CALL has proven unsuccessful. Is there a MySQL equivalent to JavaScript's eval function that would make this possible?

Answer:

Yes, the following technique provides a MySQL implementation similar to JavaScript's eval:

  1. Define an SQL variable (@queryString) using CONCAT to dynamically generate the query string from the varchar parameter.
  2. Prepare a statement (stmt) based on @queryString using PREPARE.
  3. Execute the prepared statement (stmt) using EXECUTE.
  4. Deallocate the prepared statement using DEALLOCATE PREPARE.
  5. Reset the SQL variable (@asd) to NULL.

For instance:

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;
Copy after login

The above is the detailed content of Can MySQL Execute a String as a Query Like JavaScript\'s eval()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template