how to input table as a variable in MySQL - mysql

I am trying to get data from a table using dynamic procedure with MySQL query.
Is there any way to do it specifically?
I am trying with this procedure below however the variable is still returning as a column.
See code below:
DELIMITER $
DROP PROCEDURE IF EXISTS REC_DATA$
CREATE PROCEDURE REC_DATA( IN_TABLE_NAME VARCHAR(20) )
BEGIN
BEGIN
SET #in_table = IN_TABLE_NAME;
SET #sql_stmt = CONCAT(' SELECT student_id FROM ' , #in_table);
SELECT #sql_stmt;
PREPARE stmt FROM #sql_stmt;
EXECUTE stmt;
END;
END$
DELIMITER ;
I am receiving this error: ERROR: ERROR 1054 (42S22): Unknown column 'SCORE' in 'field list'
Someone can help me?
Thanks!

I can replicate this error if I fail to enclose the parameter in the call statement with single quotes.

Follow the correct code:
DELIMITER $
DROP PROCEDURE IF EXISTS REPORT$
CREATE PROCEDURE REPORT( IN_TAB_NAME VARCHAR(20) )
BEGIN
DECLARE sql_stmt VARCHAR(100);
BEGIN
SET #in_table = IN_TAB_NAME;
SET #sql_stmt = CONCAT(' SELECT [columns] FROM ' , #in_table,
' GROUP BY [column]');
SELECT #sql_stmt;
PREPARE stmt FROM #sql_stmt;
EXECUTE stmt;
END;
END$
DELIMITER ;

Related

Incorrect parameters in the call to native function 'concat'

I am trying to create store procedure as follows
CREATE PROCEDURE `Test1` (IN projName VARCHAR(200), IN tablName VARCHAR(200))
BEGIN
set #cmd = concat('Create table', tablName ' as ( select name from samprojects.projects where type=',projName')');
PREPARE stmt FROM #cmd;
EXECUTE stmt;
END
And getting below error
ERROR 1583: Incorrect parameters in the call to native function 'concat'
Any idea how to resolve this.
I am using MYSQL workbench for running sql queries
SQL script generated by MYSQL workbench is as follows
USE `samprojects`;
DROP procedure IF EXISTS `Test1`;
DELIMITER $$
USE `samprojects`$$
CREATE PROCEDURE `Test1` (IN projName VARCHAR(200), IN tablName VARCHAR(200))
BEGIN
set #cmd = concat('Create table', tablName, ' as ( select name from samprojects.projects where type=',projName')');
PREPARE stmt FROM #cmd;
EXECUTE stmt;
END$$
DELIMITER ;
You are missing a comma after tablName:
set #cmd = concat('Create table', tablName, ' as ( select name from samprojects.projects where type=''',projName, ''')');

Mysql procedure drop table, error code 1054

I have a issue when I try to create a procedure.
First with :
DROP TABLE IF EXISTS curr_rate;
There no problem the table is dropped.
Now with a procedure :
CREATE DEFINER=`root`#`localhost` PROCEDURE `Drop_table_Gen`(IN tname varchar(20))
BEGIN
SET #query = CONCAT('DROP TABLE IF EXISTS `',tname,'`');
PREPARE stm FROM #query;
EXECUTE stm;
END
I get the following error:
error code 1054 Unknown column
The same issue if I write :
CREATE DEFINER=`root`#`localhost` PROCEDURE `drop_table_gen2`(IN tname varchar(20))
BEGIN
DROP TABLE IF EXISTS tname;
END
I hope someone has an idea about this problem
Thanks
First of all, you are calling like call Drop_table_Gen(curr_rate);. shouldn't you be quoting the parameter like call Drop_table_Gen('curr_rate'); since it's a VARCHAR type.
If still same error then I don't see anything wrong with the way you are trying to drop the table. To my believe, somehow IF EXIST is creating the problem here. Try without that (below procedure) and it will work.
CREATE PROCEDURE `Drop_table_Gen`(IN tname varchar(20))
BEGIN
SET #query = CONCAT('DROP TABLE `',tname,'`');
PREPARE stm FROM #query;
EXECUTE stm;
END
If you are using MySQL 5.5 or above then you can use EXIT HANDLER for error catching within your procedure like below
CREATE PROCEDURE `Drop_table_Gen`(IN tname varchar(20))
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
SET #error_count = #error_count + 1;
IF #a = 0 THEN RESIGNAL; END IF;
END;
BEGIN
SET #query = CONCAT('DROP TABLE `',tname,'`');
PREPARE stm FROM #query;
EXECUTE stm;
END
Then while calling the procedure
SET #error_count = 0;
SET #a = 0;
CALL Drop_table_Gen('curr_rate');
So in case, table doesn't exist it will pop up the SQL error
ERROR 1051 (42S02): Unknown table 'curr_rate'
See a detailed document here RESIGNAL Syntax

unable to store return value from execute statement in mysql

Using MySQL, I am trying to create a stored proc to retrieve the maximum value of a varchar column in any given table. I would want to increment the value of the column by 1 and then use it to store the other fields. I do not want the column to be int and auto increment.
the stored proc i have for now is
DELIMITER $$
use gounicartdb$$
DROP PROCEDURE IF EXISTS sp_getUpdatedIDFromTable$$
CREATE PROCEDURE sp_getUpdatedIDFromTable(
IN tableName varchar(50),
IN columnName varchar(50),
IN incrementValue int/*,
OUT updatedID varchar(10)*/
)
BEGIN
SET #newID = "abc";
SET #cmdString = concat("Select max(", columnName, ") from ", tableName);
PREPARE stmt FROM #cmdString;
SELECT #newID = EXECUTE stmt;
END$$
DELIMITER ;
When compiling I see no errors, but when executing the procedure the following error occurs.
14:50:48 Call sp_getUpdatedIDFromTable("user", "SNo", 1) Error Code: 1054. Unknown column 'EXECUTE' in 'field list' 0.000 sec
Please help.
You can replace in your procedure
SET #cmdString = concat("Select max(", columnName, ") into #newID from ", tableName);
PREPARE stmt FROM #cmdString;
EXECUTE stmt;
SELECT #newID;

MySQL stored procedure Error - Create table from param names

I'm trying the following but I'm getting the following error:
ERROR 1054 (42S22): Unknown column 'f' in 'where clause'
I'm seriously confused because f is a parameter of createtableTest...
CREATE PROCEDURE createtableTest
(
tname2 varchar(20),
f varchar(20)
)
BEGIN
DROP TABLE IF EXISTS tname2;
CREATE TABLE tname2 as SELECT * FROM data WHERE group_name like f;
END;
Since f is contains the value, a dynamic sql is needed so we can concatenate it with the original query,
DELIMITER $$
CREATE PROCEDURE createtableTest(IN tname2 varchar(20),IN f varchar(20))
BEGIN
DROP TABLE IF EXISTS tname2;
SET #sql = CONCAT('CREATE TABLE tname2 as SELECT * FROM data WHERE group_name like ''%',f,'%''');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;
for example, the value of f is hello, the concatenated string will produce
CREATE TABLE tname2 as SELECT * FROM data WHERE group_name like '%hello%'
UPDATE
MySQL Prepared Statements
Aside from concatenation, you can also parameterized the value which is the best way, ex
DELIMITER $$
CREATE PROCEDURE createtableTest(IN tname2 varchar(20),IN f varchar(20))
BEGIN
DROP TABLE IF EXISTS tname2;
SET #sql = CONCAT('CREATE TABLE tname2 as SELECT * FROM data WHERE group_name like ?');
PREPARE stmt FROM #sql;
SET #val = CONCAT('%', f, '%');
EXECUTE stmt USING #val;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;

Stored procedure error on CALL

I am trying to call a procedure which compiles successfully but on calling I get this error:
Query: call proc5
Error Code: 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 'NULL' at line 1
This is my Stored procedure:
DELIMITER $$
CREATE DEFINER = `root` #`localhost` PROCEDURE `proc5` ()
BEGIN
DECLARE done BOOL DEFAULT FALSE ;
DECLARE tablename VARCHAR (100) ;
DECLARE tracktables CURSOR FOR
SELECT
TABLE_NAME
FROM
information_schema.TABLES
WHERE TABLE_SCHEMA = 'db1' ;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE ;
OPEN tracktables ;
myloop :
LOOP
FETCH tracktables INTO tablename ;
IF done
THEN CLOSE tracktables ;
LEAVE myloop ;
END IF ;
SET #s = CONCAT(
'INSERT INTO db2.test1 SELECT * FROM ',
#tablename
) ;
PREPARE stmt1 FROM #s ;
EXECUTE stmt1 ;
DEALLOCATE PREPARE stmt1 ;
END LOOP ;
END $$
DELIMITER ;
Actually, I want to select all the tables from a database and insert those tables into one table which is in another database using MySQL Cursors. And when I call this stored procedure I get the above error.
The problem is that you are mixing declared variables and impromtu #vars.
var -> tablename does not equal var -> #tablename.
Change the set line to:
SET #s = CONCAT(
'INSERT INTO db2.test1 SELECT * FROM `'
,tablename
,'`'
) ;
Now it should work.
The backticks ` should not be needed, but are there just in case.