7

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.

1
  • see my answer, i think it will work Commented Apr 12, 2012 at 11:53

3 Answers 3

18

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; 
Sign up to request clarification or add additional context in comments.

2 Comments

I got this error #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EXECUTE stmt_name' at line 2
So how would you then recover the new record Id that was created by that executed query?
2
Set @query = CONCAT("INSERT INTO history VALUES (",1,",",50,",UTC_TIMESTAMP()");

and then

PREPARE stmt_name FROM @query

and at last

EXECUTE stmt_name

Comments

-2

remove the CONCAT(), it's not doing anything except generate an error since it's trying to concatenate a string with nothing else.

2 Comments

It is actually concatenting 5 elements, it wont be any error => your answer is bad -> dont answer already answered questions - look at the new section and show your skills :)
illogical answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.