Same variable in parameter in mysql store procedure - mysql

How do I cache dynamic query from store procedure?
Right now I have created my store procedure like this :
CREATE PROCEDURE usp_MyProcedure (
IN UserID INT,
....
)
BEGIN
SET #sqlQuery = CONCAT("SELECT Name From Users WHERE UserID > ", UserID, " AND UserID IN ( SELECT UserID FROM OtherTable WHERE UserID = ", UserID, " ) Order by Name")
PREPARE stmt FROM #sqlQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
But this kind of query does not cached. so, every time it gets more time to execute/process query.
Now I have tried some other method like this:
CREATE PROCEDURE usp_MyProcedure (
IN UserID INT,
....
)
BEGIN
SET #UserID = UserID;
SET #sqlQuery = "SELECT Name From Users WHERE UserID > ? AND UserID IN ( SELECT UserID FROM OtherTable WHERE UserID = ? ) Order by Name";
PREPARE stmt FROM #sqlQuery;
EXECUTE stmt #UserID, #UserID; -- here i passed same variable twice.
DEALLOCATE PREPARE stmt;
END;
In the above case I have to pass same variable (#UserID) twice, because it is used 2 times in my query. but this job is very hectic in long or complex query. so, how do I avoid this?
One another method I tried as follows:
CREATE PROCEDURE usp_MyProcedure (
IN UserID INT,
....
)
BEGIN
SET #UserID = UserID;
SET #sqlQuery = "SELECT Name From Users WHERE UserID > #UserID AND UserID IN ( SELECT UserID FROM OtherTable WHERE UserID = #UserID ) Order by Name";
PREPARE stmt FROM #sqlQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
But above query again does not cached. so, execution time is very long. and this type of variable declared as session global variable has may be conflict with another store procedure's variable. because I have call store procedure within this store procedure and variable name should be same in another store procedure.
So, let me know what is the best solution for the same.
Thanks.

Sorry just posted a mistaken one,
DELIMITER //
CREATE PROCEDURE yourprocedurenamehere(IN state CHAR(2))
BEGIN
SET #mystate = state;
SET #sql = CONCAT('SELECT * FROM BLABLABLA WHERE BLA = ?');
PREPARE stmt FROM #sql;
EXECUTE stmt USING #mystate;
END;
//
Sorry pal, just edited my code hahaha I got this wrong

A short answer is that there is no way to do it. In theory, you could identify prepared statement name with sha1(prepared statement query text), and use this as a statement handle. But there is no way to dynamically execute a statement which name is stored in a variable or in a table: EXECUTE itself is not allowed in Dynamic SQL query text.
A different question is whether you need a Dynamic SQL in your example at all, it seems like a standard SQL stored procedure parameterized with input parameters could do just fine.

Related

How to set the result of a query as a queryable table?

I am trying to use the result of a query as a table.
This query works fine:
SELECT date, number FROM `table_A`
The query below as well --> its result is table_B as a string of character not the table itself
SELECT nametable FROM `list_repository` WHERE id=1
But the combined one does not:
SELECT date, number FROM (SELECT nametable FROM `list_repository` WHERE id=1) A
I expect the resulting query to be
SELECT date, number FROM `table_B`
I tried to set a variable but it does not work either:
DECLARE x VARCHAR(150) ;
SET table=( SELECT `nametable` FROM `list_repository` WHERE id=1);
SELECT * from `table`. But it would not work
Thank you for your help!
Identifiers (db, table, column names etc) in SQL are static. Therefore you can't populate them at run-time. But you can build a query as a string and execute it via dynamic SQL. Something along the lines of
SET #sql = NULL;
SELECT CONCAT("SELECT * FROM ", nametable)
INTO #sql
FROM list_repository
WHERE id = 1;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
An example of wrapping it up into a stored procedure
DELIMITER //
CREATE PROCEDURE sp1 (IN id INT)
BEGIN
SET #sql = NULL;
SELECT CONCAT("SELECT * FROM ", nametable)
INTO #sql
FROM list_repository
WHERE id = id;
SELECT #sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END//
And then invoking it
CALL sp1(1);

Mysql multiple parameters with multiple queries inside stored procedure

I need to create a 'select' mysql procedure that will accept multiple parameters, inline with this the procedure will select to other tables
Objective
Stored procedure must accept multiple parameters
Using the multiple parameters, procedure should select on table_a, table_b and table_c
Currently i am using this code (it accepts multiple parameter but I don't know how to modify it so it would do another select on table_b and table_c)
DELIMITER //
CREATE PROCEDURE select_multiple_object(IN user_ids VARCHAR(65535))
BEGIN
SET #query = CONCAT ('SELECt * FROM table_a WHERE userid IN (',user_ids,')');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
What I really want to achieve is something like this:
DELIMITER //
CREATE PROCEDURE select_multiple_object(IN user_ids VARCHAR(65535))
BEGIN
SET #query = CONCAT ('
SELECt * FROM table_a WHERE userid IN (',user_ids,');
SELECt * FROM table_b WHERE userid IN (',user_ids,');
SELECt * FROM table_c WHERE userid IN (',user_ids,');
');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
CALL select_multiple_object('1,2,3')
Assemble your MySQL query first, then send the query, similar to the following:
$parameter = "user_ids";
$table = "table_a";
$query = 'SELECT * FROM ' . $parameter . ' WHERE userid IN (",' . $parameter . ',")';
$result = mysql_query($query);
To input multiple parameters, simply use a loop to repeat this process as needed.

Calling stored procedure with a string to use in query

I have a stored procedure where i need to pass a string to use in the query.
Stored procedure example:
BEGIN
SET #query = query;
SELECT * FROM test WHERE #query
END
How I would like to call it with a string:
CALL proceduretet('activity_id = 1 OR activity_id = 2')
The query can be different each time, sometimes there will be 1 activity_id and sometimes 4 or more.
I have tried to pass it as a varchar and text, but it won't work.
So is there a way to pass a string to stored procedures and use it in the query?
Regards, Andreas
The code would look like:
BEGIN
SET #query = query;
SET #sql = concat('SELECT * FROM TEST WHERE ', #query);
PREPARE stmt from #sql;
EXECUTE stmt;
END;

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;

use a variable for table name in mysql sproc

I'm trying to pass a table name into my mysql stored procedure to use this sproc to select off of different tables but it's not working...
this is what I"m trying:
CREATE PROCEDURE `usp_SelectFromTables`(
IN TableName varchar(100)
)
BEGIN
SELECT * FROM #TableName;
END
I've also tried it w/o the # sign and that just tells me that TableName doesn't exist...which I know :)
SET #cname:='jello';
SET #vname:='dwb';
SET #sql_text = concat('select concept_id,concept_name,',#vname,' from enc2.concept a JOIN enc2.ratings b USING(concept_id) where concept_name like (''%',#cname,'%'') and 3 is not null order by 3 asc');
PREPARE stmt FROM #sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
An extra bit that caused me problems.
I wanted to set the table name and field dynamically in a query as #kyle asked, but I also wanted to store the result of that query into a variable #a within the query.
Instead of putting the variable #a into the concat literally, you need to include it as part of the string text.
delimiter //
CREATE PROCEDURE removeProcessed(table_name VARCHAR(255), keyField VARCHAR(255), maxId INT, num_rows INT)
BEGIN
SET #table_name = table_name;
SET #keyField = keyField;
SET #maxId = maxId;
SET #num_rows = num_rows;
SET #sql_text1 = concat('SELECT MIN(',#keyField,') INTO #a FROM ',#table_name);
PREPARE stmt1 FROM #sql_text1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
loop_label: LOOP
SET #sql_text2 = concat('SELECT ',#keyField,' INTO #z FROM ',#table_name,' WHERE ',#keyField,' >= ',#a,' ORDER BY ',#keyField,' LIMIT ',#num_rows,',1');
PREPARE stmt2 FROM #sql_text2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
...Additional looping code...
END LOOP;
END
//
delimiter ;
So in #sql_text1 assign the result of the query to #a within the string using:
') INTO #a FROM '
Then in #sql_text2 use #a as an actual variable:
,' WHERE ',#keyField,' >= ',#a,' ORDER BY '
It depends on the DBMS, but the notation usually requires Dynamic SQL, and runs into the problem that the return values from the function depend on the inputs when it is executed. This gives the system conniptions. As a general rule (and therefore probably subject to exceptions), DBMS do not allow you to use placeholders (parameters) for structural elements of a query such as table names or column names; they only allow you to specify values such as column values.
Some DBMS do have stored procedure support that will allow you to build up an SQL string and then work with that, using 'prepare' or 'execute immediate' or similar operations. Note, however, that you are suddenly vulnerable to SQL injection attacks - someone who can execute your procedure is then able to control, in part, what SQL gets executed.