3

I would like to make dynamic queries in within my procedure. SQL Server has neat sp_executesql procedure for such tasks, is there anything in MySQL which can help me to achieve similar functionality?

Deka
  • 131
  • 1
  • 4
  • 12

2 Answers2

8

AFAIK there is nothing exactly same. However, you can use a prepared statement, like:

mysql> PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql> SET @a = 3;
mysql> SET @b = 4;
mysql> EXECUTE stmt1 USING @a, @b;
+------------+
| hypotenuse |
+------------+
|          5 |
+------------+
mysql> DEALLOCATE PREPARE stmt1;

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

OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57
3

You will probably have to use prepared statements for that purpose using MySQL:

SET @query = 'INSERT INTO tbl (a) VALUES (?)';
PREPARE stmt FROM @query;

...
SET @param = 'hello';
EXECUTE stmt USING @param;
...

DEALLOCATE PREPARE stmt;
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125