MySQL stored procedure dynamic sql result - mysql

I understand it's possible to have dynamic SQL in user defined stored procedure on MySQL (>=5.0.13). So if we have something like this:
CREATE PROCEDURE test()
BEGIN
SET #query = "SELECT * FROM temp";
PREPARE stmt FROM #query;
EXECUTE stmt;
END
My question is: how can I use the result of the dynamic statement that is executed?

If the result is a single value you can load it into a variable.
If your query retrieves a result set of multiple records you can load these into a cursor and loop through them record by record for further processing. See http://dev.mysql.com/doc/refman/5.0/en/cursors.html

Related

How to pass multiple insert queries into MySql stored procedure?

This is my stored procedure in MySQL and I want to pass a string of multiple insert queries
CREATE DEFINER=`root`#`localhost` PROCEDURE `test_stringQry`(IN qry varchar(500))<br>
BEGIN <br>
SET #input = qry; <br>
PREPARE stmt FROM #input; <br>
EXECUTE stmt;<br>
DEALLOCATE PREPARE stmt;<br>
END
When I pass a single query it works but when I pass two or more queries it gives an error
Example:
call test.test_stringQry("INSERT INTO `test`.`products`(`pro_name`,`pro_price`) VALUES('test',900.00);INSERT INTO `test`.`products`(`pro_name`,`pro_price`) VALUES('test',900.00)")

How to recieve a query from parameter in mysql stored procedure

I have a stored procedure where I want to perform a INSERT operation. My INSERT query is stored in a php variable $query and I want to pass it as a parameter to my stored procedure.
$query_procedure = "CALL AddStation('$query','#LID')"
How can I get this query when I am creating the stored procedure?
Actually I want to use the same stored procedure for different INSERT queries
so that I dont have to pass individual parameters to the stored procedure.
Although you can technically achieve this, as shown below, I strongly discourage you from doing it. This a very bad idea. It simple doesn't make any sense and adds no value to your code. It's vulnarable to sql injections. You loose ability to use prepared statements for insert statements themselves. It's fragile and prone to errors since you're passing query strings, etc...
You better off without a stored procedure like this at all. Just use prepared statements in your client code.
DELIMITER$$
CREATE PROCEDURE AddARow(IN _sql TEXT, OUT _lid INT)
BEGIN
SET #sql = _sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
SET _lid = LAST_INSERT_ID();
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
Sample usage:
SET #lid = NULL;
SET #sql = 'INSERT INTO tablest (STATION_NAME, GEOGRAPHY) VALUES (''station1'',''India'')';
CALL AddARow(#sql, #lid);
SELECT #lid;
Here is SQLFiddle demo

Execute multiple semi-colon separated query using mysql Prepared Statement

I am trying to create a stored procedure in mysql which creates a new table on every request copies the content from another table and extracts the required data and finally drops the table. The stored procedure is quite large so I cant have EXECUTE after every query and thus I am trying to execute the query all together in a semicolon separated format. But on final execution I get Error Code: 1064.
Is the approach I am trying possible, or is there a better approach.
SET tableName = (SELECT CONCAT("table",(UNIX_TIMESTAMP(NOW()))));
SET #tquery =CONCAT('CREATE TABLE `',tableName,'` (select pt.* from post_table pt join on user u on pt.user_id=u.id where pt.client="client",pt.group="group");');
SET #tquery = CONCAT(#tquery,' SELECT * FROM ',tableName,';');
SET #tquery = CONCAT(#tquery,' DROP TABLE ',tableName,';');
PREPARE stmt FROM #tquery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
No, it is not possible. PREPARE / EXECUTE stmt can execute only one query at a time, many statements cannot be combined. See documentation: http://dev.mysql.com/doc/refman/5.0/en/prepare.html
... a user variable that contains the text of the SQL statement. The text must represent a single statement, not multiple statements.
Anyway, to simplify your code I would create a simple procedure:
CREATE PROCEDURE exec_qry( p_sql varchar(100))
BEGIN
SET #tquery = p_sql;
PREPARE stmt FROM #tquery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
/
and I would call this procedure in the main procedure, in this way:
CALL exec_qry( 'CREATE TABLE t2 AS SELECT * FROM test');
CALL exec_qry( 'SELECT * FROM t2');
CALL exec_qry( 'SELECT count(*) FROM t2');
CALL exec_qry( 'SELECT avg(x) FROM t2');
CALL exec_qry( 'DROP TABLE t2');
Take a look at a demo: http://www.sqlfiddle.com/#!2/6649a/6

How to run mysql queries that are stored in a mysql table using a procedure

I am developing a simple WPF(C#) application where i am storing all insert, update and delete queries in a table. These queries are then executed on server one by one by simply selecting and then executing using ExecuteNonQuery() function in c#. The problem is that if have a large number of queries then it becomes very slow and sometimes due to network connection it is falling out.
Is it possible to create a stored procedure that can execute the queries stored within a table on the same server?
Please answer as soon as possible. Thanks.
Here is some code that i have tried till now.
DELIMITER $$
CREATE PROCEDURE `MyProc`(wo varchar(100))
BEGIN
DECLARE x INT;
DECLARE str text;
set x = 0;
select count(*) into x from tblqueries where isexecutedonserver = false and woid = wo;
SET str = '';
REPEAT
select `query` into str from tblqueries where id = 2976;
SET x = x - 1;
UNTIL x > 0
END REPEAT;
##select str;
prepare stmt from #str;
execute stmt;
deallocate prepare stmt;
END $$
DELIMITER ;
Please check and tell me where I am wrong.
This is simple (as simple as googling "mysql stored procedure execute")
Declare a CURSOR in your stored procedure.
Execute the cursor, then prepare a statement with the output:
PREPARE stmt FROM #sql;
EXECUTE stmt USING #myvar;
This code will help you with it:
MySQL Pass table name to cursor select
It sounds like what you need is a view.
Views (including updatable views) are available in MySQL Server 5.0. Views are stored queries that when invoked produce a result set. A view acts as a virtual table. Views are available in binary releases from 5.0.1 and up.
http://dev.mysql.com/doc/refman/5.0/en/views.html

Prepared statement returning zero results

I am attempting to execute the following prepared statement:
PREPARE stmt FROM 'SELECT * FROM Inventory I WHERE I.ParentId = ?';
EXECUTE stmt USING #parentId;
DEALLOCATE PREPARE stmt;
When I execute this statement, it returns the column headers with no rows. It should return 6 rows.
If I execute this same statement as a normal SQL statement without the PREPARE and EXECUTE statement, I get results, e.g.
SELECT * FROM Inventory I WHERE I.ParentId = parentId;
Results are returned. What am I doing wrong? Is there some kind of casting going on that is making my statement invalidate?
Update, parentId is passed in as a parameter, e.g.
CREATE DEFINER=`george`#`%` PROCEDURE `ListInventoryByParentId`(IN parentId INT)
User variable #parentId and procedure argument parentID are independent.
You need to set your user variable to procedure argument before executing statement.
SET #parentID = parentId;