0

I am trying to write a generic sql procedure that can execute any string as a sql statement.

Here is the procedure definition.

DELIMITER //

DROP PROCEDURE IF EXISTS execute_dynamic_sql;
CREATE PROCEDURE execute_dynamic_sql (IN sql_query longtext)
BEGIN
SELECT sql_query;
PREPARE stmt FROM @sql_query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //

I am calling the above function like this

mysql> call execute_dynamic_sql('show tables');
    -> //
+-------------+
| sql_query   |
+-------------+
| show tables |
+-------------+
1 row in set (0.00 sec)

ERROR 1064 (42000): 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 'NULL' at line 1
mysql> #

Can somebody tell me why is the error coming ?

2
  • ... Why are you writing a procedure to execute a query? Why not just execute the query? Commented Jan 26, 2015 at 13:06
  • I have to make a lot of sql statements and execute it. So, I moved the 4 common lines to another procedure. Commented Jan 26, 2015 at 13:09

1 Answer 1

2

It is important to indicate the difference between 9.4. User-Defined Variables and routine parameters 13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax, are different variables.

In your example @sql_query is NULL and sql_query is assigned to SHOW TABLES.

Try:

DELIMITER//

CREATE PROCEDURE `execute_dynamic_sql` (IN `sql_query` LONGTEXT)
BEGIN
  SET @`sql_query` := `sql_query`;
  PREPARE `stmt` FROM @`sql_query`;
  EXECUTE `stmt`;
  DEALLOCATE PREPARE `stmt`;
END//

DELIMITER;

SQL Fiddle demo

Sign up to request clarification or add additional context in comments.

Comments

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.