sql run querys since procedures [duplicate] - mysql

This question already has answers here:
Mysql stored procedure don't take table name as parameter
(4 answers)
Closed 6 years ago.
I tried do query since one procedure in mysql
I followed the following:
DELIMITER #
CREATE PROCEDURE returndata(IN xtable CHAR(255), IN xcolumn CHAR(255))
BEGIN
IF (xcolumn = 'XALL') THEN
SELECT * FROM xtable;
ELSE
SELECT xcolumn FROM xtable;
END IF;
END;
#
DELIMITER ;
but gives error. any help is acceptable, or I might say if this is possible?
EDIT error to call the procedure:
MariaDB [pruebab]> CALL returndata('test', 'id');
ERROR 1146 (42S02): Table 'pruebab.xtable' doesn't exist

You cannot pass a table name as a parameter like that. You need to concatenate the variables into an SQL string to use them. See this answer.
Mysql stored procedure don't take table name as parameter

Variables are only evaluated in expressions in queries, not where column or table names are required. You need to use a prepared query.
CREATE PROCEDURE returndata(IN xtable CHAR(255), IN xcolumn CHAR(255))
BEGIN
IF (xcolumn = 'XALL') THEN
SET #SQL = CONCAT('SELECT * FROM ', xtable);
ELSE
SET #SQL = CONCAT('SELECT ', xcolumn, ' FROM ', xtable);
END IF;
PREPARE stmt FROM #SQL;
EXECUTE stmt;
END;

Related

SELECT JSON_ARRAYAGG FROM TABLE name as parameter problem

I want to have a MySQL procedure, that makes SELECT FROM table and return the result in JSON format via JSON_ARRAYAGG, but the table name to be a parameter.
So there is my solution, but it doesn't work when I call it, because the system thinks the parameter is table name. I will be very thankful if someone can help me.
CREATE DEFINER=`ME` PROCEDURE `main_list`(
IN `the_table` CHAR(50)
)
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
BEGIN
SELECT JSON_ARRAYAGG(JSON_OBJECT('id', id,'name', NAME)) from the_table;
END
The call and error:
CALL `main_list`('martin');
/* SQL Error (1146): Table 'my_server.the_table' doesn't exist */
As Akina and gotgn already said you can't use tablename in that way and in some other ise PREPARE Statetemnts for it
DELIMITER //
CREATE PROCEDURE `main_list`(
IN `the_table` CHAR(50)
)
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
BEGIN
SET #sql := CONCAT("SELECT JSON_ARRAYAGG(JSON_OBJECT('id', id,'name', NAME)) FROM ",the_table);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END//
DELIMITER ;

MySQL Stored Procedure basics

This looks like a pretty rudimentary question but for someone who is new to MySQL, it has proven to be a tough nut to crack.
I've been trying to create a stored procedure in the MySQL and this is what I tried:
CREATE DEFINER=`root`#`localhost` PROCEDURE `test_procedure`(
IN dtst_nm varchar(42)
)
BEGIN
SELECT
COUNT(*)
FROM
data_hub.dtst_nm
;
END
When I run this, I get the error that dtst_nm doesn't exist. The exact error message is:
"Error Code: 1146. Table 'data_hub.dtst_nm' doesn't exist"
Clearly the variable is not getting resolved.
From what I gathered, the syntax seems to be right. What am I missing?
This is a Dynamic SQL problem. You cannot directly specify variables in place of table and column names. You will need to use string functions of create SQL query string. Then use Prepare with Execute to run the query.
Try:
DELIMITER $$
DROP PROCEDURE IF EXISTS `test_procedure` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `test_procedure`(
IN `dtst_nm` varchar(42)
)
BEGIN
SET #s = CONCAT('SELECT COUNT(*) FROM ', dtst_nm );
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;

MySql column names of a query

Am I able to write a stored procedure with a parameter, which is the mysql query and the stored procedure returns the column names of the query?
For example I call the procedure:
call selector('select * from users')
And the procedure returns the column names.
It would be easy with information.schema but if I have a more complicated query and alias in it?
Found a solution
CREATE DEFINER=`admin`#`localhost` PROCEDURE `selector`(
IN `sql_query` VARCHAR(50))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGiN
drop table if exists tmp111;
SET #sql = concat('create table tmp111 as ', sql_query);
PREPARE stmt FROM #sql;
Execute stmt;
describe tmp111;
END
Then call it like:
call selector('select name as n, email as e from users')

How to write a mysql function with dynamic table name?

I'm trying to write a my sql function doing the following things:
1- get the table name used in join as a parameter.
but I get mysql syntax error
1064 - 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 'table DETERMINISTIC
BEGIN select `r`.`id` AS `id`, (case ' at line 2
This is my query
DELIMITER $$
CREATE FUNCTION getTranslation (tablename varchar(50),entity varchar(20),itemid int,lang char(3))
RETURNS table
DETERMINISTIC
BEGIN
select
`r`.`id` AS `id`,
(case
when isnull(`t`.`descr`) then `r`.`descr_ml`
else `t`.`descr`
end) AS `descr`
from
(tablename `r`
left join `g001_translation` `t` ON ((`t`.`item_id` = `r`.`id`)))
END$$
DELIMITER ;
I the select part works fine with static table name by the way.
First up as mentioned by #eggyal this isn't the best way to go about things. But it can be done by using prepared statements. I.e.
DROP PROCEDURE IF EXISTS `exampleOfPrepareStatement`;
CREATE DEFINER = `user`#`%` PROCEDURE `exampleOfPrepareStatement`(inTableName VARCHAR(100))
MODIFIES SQL DATA
SQL SECURITY INVOKER
BEGIN
SET #hr1 = CONCAT('
INSERT INTO `',inTableName,'` (
-- fields (can use parameters same as table name if needed)
)
-- either VALUES () or SELECT here
');
-- Prepare, execute, deallocate
PREPARE hrStmt1 FROM #hr1;
EXECUTE hrStmt1;
DEALLOCATE PREPARE hrStmt1;
END;
You can of course add in field names etc. as needed, or use a SELECT or UPDATE etc. This is not ideal, but will do what you are looking for.
I have had to use this in some places before where the same maintenance is being performed on multiple tables which have different field names ( / table names ) and so instead of writing the same function 20 times, instead I use this type of stored procedure which can then be called to do the indexing etc.
As also mentioned by #eggyal , while this may do as you ask, it might not do as you need. If you can provide more information then you may get a better solution.
Give this a try
SET #ex = CONCAT('select `r`.`id` AS `id`,(case when isnull(`t`.`descr`) then `r`.`descr_ml` else `t`.`descr` end) AS `descr` from (',tablename,' `r` left join `g001_translation` `t` ON ((`t`.`item_id` = `r`.`id`)));');
PREPARE stmt FROM #ex;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
You will notice that ',tablename,' will use the parameter passed.

CALL statement syntax error when passing multiple parameters mySql

I am running a query in MySQL 5.6.11. I have created a following stored procedure
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `digital_audio_test_detail`(IN temp VARCHAR(50), IN temp2 VARCHAR(50))
BEGIN
SET #temp_query = CONCAT('SELECT * FROM ',temp);
SET #final_query = CONCAT(#temp_query,'WHERE', temp,'.unit_test_result_id =',temp2);
PREPARE stmt FROM #final_query;
EXECUTE stmt;
END
When I call this procedure in my query page, I get syntax error at its CALL. This is how I execute my queries.
SELECT unit_test_result.*, #temp1 := unit_test.name, #temp2 := unit_test_result.id
FROM unit_test_result, unit_test
WHERE unit_test_result.test_run_id = 2
AND unit_test.id = unit_test_result.unit_test_id;
CALL digital_audio_test_detail(#temp1, #temp2);
I have to pass two parameters to the procedure. When I create a procedure with only first parameter and CALL it one parameter, it executes fine. But When I do with two parameters I get syntax error. Need help. Thanks
SET #final_query = CONCAT(#temp_query,'WHERE', temp,'.unit_test_result_id =',temp2);
The string you are building is not a valid query.
Add space before and after WHERE, as in
SET #final_query = CONCAT(#temp_query,' WHERE ', temp,'.unit_test_result_id =',temp2);