Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute mysql query present in variable

I have a MySQLvariable

@query = CONCAT('INSERT INTO history VALUES (',1,',',50,',UTC_TIMESTAMP()');

I want to execute the insert statement present in the variable.

like image 403
Avinash Avatar asked Apr 12 '12 11:04

Avinash


People also ask

What is @@ in MySQL?

@@ is used for system variables. Using different suffix with @@ , you can get either session or global value of the system variable.

What is dynamic SQL in MySQL?

Dynamic SQL is a programming technique you can use to build SQL statements as textual strings and execute them later. This technique could prove to be useful in some cases and therefore it's good to know we have it as an option. In today's article, we'll show how to create and execute dynamic SQL statements.


2 Answers

You must first prepare the statement using PREPARE and then use EXECUTE

See here: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html

Something like:

SET @query = CONCAT("INSERT INTO history VALUES (",1,",",50,",UTC_TIMESTAMP()");

PREPARE stmt1 FROM @query; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1; 
like image 77
mattytommo Avatar answered Nov 03 '22 02:11

mattytommo


Set @query = CONCAT("INSERT INTO history VALUES (",1,",",50,",UTC_TIMESTAMP()");

and then

PREPARE stmt_name FROM @query

and at last

EXECUTE stmt_name
like image 29
Ankit Sharma Avatar answered Nov 03 '22 01:11

Ankit Sharma