How to excute something what is inside a variable in MySQL? - mysql

I have a problem what I can solve in PHP but I want to solve in MySQL. Basicley I have a stored function, TASK_ASSIGN(id_task, operator).
I have an other function what SELECT exec FROM tasks. The tasks has a column exec, inside there I save TASK_ASSIGN(id_task, operator) format to execute.
I want to execute in a stored function or procedure if it is possible. Somebody can help me?

The solution was a stored procedure with this source:
BEGIN
DECLARE $execute_function VARCHAR(100);
-- Get the waiting function for execution
SELECT `exec` INTO $execute_function FROM `tasks` WHERE `id_task` = '1';
-- Create a session variable with the complete select
SET #query = CONCAT("SELECT ",$execute_function," AS result");
-- Execute the custom query
PREPARE execute_query FROM #query;
EXECUTE execute_query;
DEALLOCATE PREPARE execute_query;
END;
Thanks for wchiquito for suggesting the Prepared Statements.

Related

MYSQL variable with CURSOR and FETCH

I wanted to use table names and run a statement with the table name as variable. I used cursor/fetch but when I run a statement with the variable it is not using the value of the variable but just seems to use the variable_name itself. I have seen example with concat where another variable was defined but what if I just wanted to reference the table name in a COMMAND?
DELIMITER $$
DROP PROCEDURE IF EXISTS test $$
CREATE PROCEDURE test()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE v_table_name TEXT;
DECLARE cur1 CURSOR FOR
SELECT TABLE_NAME FROM information_schema.tables where table_schema = 'rt';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done= TRUE;
OPEN cur1;
myloop: loop
FETCH cur1 INTO v_table_name;
IF done THEN
LEAVE myloop;
END IF;
COMMAND table v_table_name;
END loop;
close cur1;
END $$
If by COMMAND you mean you want to use the value of a variable as an identifier in another SQL statement... you may be able to make use of a prepared statement (in the context of a MySQL stored program).
Reference: https://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html
As a trivial example of what that might look like:
SET #sql = CONCAT('select * from `',v_table_name,'` limit 1');
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SET #sql = NULL;
Note that this approach is not safe from SQL Injection vulnerabilities.
If that's not what you are looking for, I'm at a loss. I don't understand what you are referring to as a COMMAND.

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

MySQL stored procedure dynamic sql result

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

Iterate MySQL schemas

Problem description
I have a single-tenant MySQL database setup. That is, I have one identical schema for each client.
Now I need to run a specific query for each client. That would be easy in a multi-tenant setting (where all clients share a single schema). With my setup however, I need to iterate the schemas. More generally, I want to access a schema whose name is given by a variable. How can that be done?
What I've tried
If I try USE varSchemaName (where varSchemaName is a varchar
variable), I get the error message ERROR 1314: USE is not allowed
in stored procedures.
If I try SELECT * FROM varSchemaName.MyTable I get
Error Code: 1146. Table 'varSchemaName.MyTable' doesn't exist. Apparently MySQL considers varSchemaName to be a literal, not a
variable.
Building on the answer from fancyPants, you can call that procedure within a loop from another procedure which queries information_schema.tables to identify the databases containing MyTable and then call fancyPants' procedure with the db names as a parameter. This method is easy if the databases have a consistent naming scheme or contain identically named objects, which sounds like the case here. The structure would be something like:
DELIMITER //
DROP PROCEDURE IF EXISTS mydriver //
CREATE PROCEDURE mydriver()
BEGIN
DECLARE varSchemaName VARCHAR(64);
DECLARE done BOOLEAN;
DECLARE cur CURSOR FOR
SELECT table_schema
FROM information_schema.tables
WHERE table_name = 'MyTable';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO varSchemaName;
IF done THEN
LEAVE read_loop;
CLOSE cur;
END IF;
CALL fancypants_proc(varSchemaName);
END LOOP;
END //
DROP PROCEDURE IF EXISTS fancypants_proc //
CREATE PROCEDURE fancypants_proc(IN varSchemaName VARCHAR(64))
BEGIN
SET #sql = CONCAT('SELECT * FROM ', varSchemaName, '.MyTable');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
CALL mydriver();
You have to build the statement first.
SET #sql = CONCAT('SELECT * FROM ', varSchemaName, '.MyTable');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
You can read more about prepared statements here.
You might be tempted to use variables for tablenames, but that doesn't work. Those parameters are for values in where clauses and so on. The above way is the way to go.

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