Can I use a String as a WHERE CLAUSE - mysql

Can anybody help me with this JSP problem.
Im trying to update the database using code similar to this:
So, I have this on my Servlet:
String QueryCondition = "id = 1";
That will be passed to this stored procedure:
CREATE
DEFINER=`root`#`localhost`
PROCEDURE `storedprocedure_1`(QueryCondition TEXT)
BEGIN
UPDATE users SET name = 'John'
WHERE QueryCondition;
END
I was thinking if this is possible because the update always fail.
If this isn't possible can you recommend how can i do such thing

You can use it in a stored procedure but with a prepared statement.
Example:
DELIMITER //
CREATE
DEFINER=root#localhost
PROCEDURE storedprocedure_1(QueryCondition TEXT)
BEGIN
SET #query := CONCAT( 'UPDATE users SET name = \'John\' WHERE ',
QueryCondition );
PREPARE stmt FROM #query;
EXECUTE stmt;
DROP PREPARE stmt;
END;
//
DELIMITER ;

Related

MySQL: How creating a function that queries with variables columns names

I am trying to make a function witch create a new ID from any table given as parameter.
DROP FUNCTION IF EXISTS create_id;
DELIMITER $$
CREATE FUNCTION create_id(db_table TEXT,pkey TEXT,strlen INT,joinner TEXT)
RETURNS TEXT
BEGIN
DECLARE max_id TEXT;
DECLARE new_id TEXT;
SET max_id = (SELECT MAX(pkey) FROM db_table);
SET new_id = max_id;
RETURN new_id;
END;
$$
DELIMITER ;
Thank you for your answers
You can't use variables like you want to; basically, if you want a variable identifier (table name, column name or the-like), you need to use dynamic SQL. But MySQL functions do not support dynamic SQL. So, instead, you need to use a procedure with an OUT paramter.
Consider:
drop procedure if exists create_id;
delimiter $$
create procedure create_id(in _db_table text, in _pkey text, out _max_id int)
begin
set #max_id = null;
set #sql = concat('select max(`', _pkey, '`) into #max_id from `', _db_table, '`');
prepare stmt from #sql;
execute stmt;
deallocate prepare stmt;
set _max_id = #max_id;
end;
$$
delimiter ;
Then, you invoke the procedure and recover the out value like so:
call create_id('mytable', 'id', #max_id);
select #max_id;
Note: I couldn't see the point for the last two arguments to your original function, so I removed them.

passing table name in stored procedure

I am trying to figure out how I can pass part of a table name into a stored procedure and get it to work.
query is
DELIMITER $$
DROP PROCEDURE IF EXISTS vorpaldev.searchLogId2$$
CREATE DEFINER = 'root'#'%'
PROCEDURE vorpaldev.searchLogId2 (userId varchar(300))
BEGIN
SET userId = CONCAT("log", userId);
SET #statment = "Select * from #userId ";
PREPARE stmt FROM #statment;
SET #a = userId;
EXECUTE stmt USING #a;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER
;
I am using
CALL searchLogId2 (131)
to call the code
I want the end results to execute as
Select * from log131
Well! are you going to create seperate table for each user????????? If yes, that is really bad.
I don't know but may be this is your answer. Why dont you pass complete userId in parameter argument 'log131' as
BEGIN
SET #statment = concat('Select * from ',userId);
PREPARE stmt FROM #statment;
EXECUTE stmt USING userId;
DEALLOCATE PREPARE stmt;
END
this will remove overhead of concat

How to pass a subquery as a parameter to a MySQL procedure?

Is there a way I could pass a whole subquery as a parameter to my MySQL function and execute it under a condition? Something (but less faulty) like this..
delimiter //
create procedure myFunction (mySubquery)
begin
if (true) then
execute mySubquery;
end if;
/*rest of the action*/
end //
delimiter ;
You could pass the query as a good ol'string (a.k.a. VARCHAR) and prepare a statement from it:
CREATE PROCEDURE proc (param VARCHAR(100))
BEGIN
SET #query = param;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #query = NULL;
END;
-- later on...
CALL proc('SELECT 1');
N.B. the ugly SET #query = param; workaround is required because "A statement prepared in stored program context cannot refer to (...) function parameters". (i.e. PREPARE stmt FROM param; is not allowed). Yuck.
You should add an error handler to such a procedure, because a broken query may (will eventually, as per Moore's law ;) be provided as a parameter. Your procedure should be prepared to handle this case gracefully.
try like this:
delimiter //
drop procedure if exists myFunction;
create procedure myFunction (mySubquery varchar(500))
begin
if (true) then
SET #mySubquery = mySubquery;
PREPARE stmt FROM #mySubquery;
EXECUTE stmt;
end if;
/*rest of the action*/
end //
delimiter ;

what is wrong with MySQL select Store Procedure with dynamic query

i have tried to create MySQL store procedure in that i want to make dynamic query.
code on which i working..
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`selectp` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `selectp`(in a_str_Condition varchar(500))
BEGIN
SET #Query = 'SELECT * from test123';
IF a_str_Condition != ''
THEN
SET #strCondition = CONCAT(' WHERE ? ');
SET #param = a_str_Condition;
ELSE
SET #strCondition = ' Order by aaa desc';
END IF
SET #Query = CONCAT(#Query, #strCondition );
PREPARE stmt FROM #Query;
EXECUTE stmt USING #param;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;
here i want pass parameter as aaa = 3 and concat it with mysql query, but it show me error as below.
please let me clear on this store procedure. Any help will be Appreciate.
Trying to answer to your ...what is wrong with MySQL select Store Procedure..?
As others mentioned you have ; missing. That only solves a syntax error.
But you have bigger problems with the way you try to construct your query and EXECUTE it:
You're incorrectly trying to treat all where conditions as one parameter with WHERE ?, instead of parameterizing values like WHERE id = ?
In case you don't pass a condition you can't use USING in EXECUTE. It'll fail.
Now since you don't execute your query multiple times, you pass conditions as a string anyway, and it seems that you're more after flexibility than security, IMHO there is no much sense in using parameters here.
That being said a more succinct version of your SP might look like this
DELIMITER $$
CREATE PROCEDURE selectp(IN _conditions VARCHAR(500), IN _orderby VARCHAR(500))
BEGIN
SET #sql = CONCAT(
'SELECT * FROM test123 WHERE 1 = 1',
COALESCE(CONCAT(' AND ', NULLIF(_conditions, '')), ''),
' ORDER BY ',
COALESCE(NULLIF(_orderby, ''), 'id DESC')
);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
Usage examples:
-- default parameters either with null or an empty string
CALL selectp('', '');
CALL selectp(NULL, NULL);
-- set where conditions
CALL selectp('id IN(1, 3)', NULL);
-- set order by
CALL selectp(NULL, 'col1 DESC, col2');
Here is SQLFiddle demo
You've lost a semicolon after END IF.
And that's what mysql is pointed you to - it always shows you the expression part it couldn't parse. So always look at the code right before the one from the error description.
There should be a semi column after the END IF statement:
ELSE
SET #strCondition = ' Order by aaa desc';
END IF; //add semicolumn here
Before this line:
SET #Query = CONCAT(#Query, #strCondition );

MySQL stored procedures - How to use parameter in FROM clause

I have the following stored procedure:
DELIMITER ///
CREATE PROCEDURE tmp_test_proc(__TABLE__NAME varchar(255))
BEGIN
SELECT COUNT(*) FROM __TABLE__NAME;
END///
DELIMITER ;
I would like to select from the parameter __TABLE__NAME, but MySQL tells me there is no table __TABLE__NAME... So is there a way to use the value of the parameter in the from clause?
you cannot parameterized table names (as well as column names) by default, you need to create PreparedStatement for this,
DELIMITER ///
CREATE PROCEDURE tmp_test_proc(__TABLE__NAME varchar(255))
BEGIN
SET #sql = CONCAT('SELECT COUNT(*) FROM ', __TABLE__NAME);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END///
DELIMITER ;