Mysql stored procedure dynamic select with out variable - mysql

When I didn't use out variable, the stored procedure worked correctly, but when I execute the stored procedure with out variable, this error shows up:
MySQL said: #1327 - Undeclared variable: sp_result
Code:
CREATE DEFINER=`root`#`localhost` PROCEDURE `test3`(OUT `sp_result` INT(11), IN `sp_where_param` VARCHAR(100), IN `sp_where_value` VARCHAR(100), IN `sp_table_name` VARCHAR(100))
NO SQL
BEGIN
DECLARE tbl_id VARCHAR(100);
SET tbl_id = CONCAT(sp_table_name,'_id');
SET #temp1=CONCAT('SELECT count(',tbl_id,') INTO sp_result FROM ',sp_table_name,' WHERE ',sp_where_param,' = \'',sp_where_value,'\'');
PREPARE stmt1 FROM #temp1;
EXECUTE stmt1;
END
Maybe without out variable also doesn't work :(

Try to use user variable -
CREATE DEFINER = 'root'#'localhost'
PROCEDURE test3 (OUT `sp_result` int(11), IN `sp_where_param` varchar(100), IN `sp_where_value` varchar(100), IN `sp_table_name` varchar(100))
NO SQL
BEGIN
DECLARE tbl_id varchar(100);
SET tbl_id = CONCAT(sp_table_name, '_id');
SET #temp1 = CONCAT('SELECT COUNT(', tbl_id, ') INTO #sp_result FROM ', sp_table_name, ' WHERE ', sp_where_param, ' = \'', sp_where_value, '\'');
PREPARE stmt1 FROM #temp1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
set sp_result = #sp_result;
END
...and add DEALLOCATE PREPARE statement.

it should be-
SET tbl_id = CONCAT(sp_table_name,'_id');
SET #temp1=CONCAT('SELECT count(',tbl_id,') INTO
like this
SET #tbl_id:= CONCAT(sp_table_name,'_id');
SET #temp1:=CONCAT('SELECT count(',tbl_id,') INTO

Related

Creating a Procedure prior to the creation of database and table

I am trying to create a Procedure during the creation of a database, the mysql query is as follows:
CREATE DATABASE database_Sensor1;
USE database_Sensor1;
CREATE TABLE Persons(id int NOT NULL);
DELIMITER //
CREATE PROCEDURE MYLOOP() IF database_Sensor1 EXISTS
BEGIN
DECLARE i int;
DECLARE str varchar(255);
SET i = 0;
WHILE i < 32 DO
SET str = CONCAT('col_',i);
SET #sql = CONCAT('ALTER TABLE persons ADD ',str,' float;');
SET i = i + 1;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END WHILE;
END
DELIMITER ;
CALL MYLOOP();
But I get this error:
#1305 - PROCEDURE database_sensor1.MYLOOP does not exist
I am trying to use the Procedure to Loop the table creation by quickly altering the table to add 32 columns in so that I can run another .php to add in the values.
CREATE DATABASE database_Sensor1;
USE database_Sensor1;
CREATE TABLE database_Sensor1.Persons(id int NOT NULL);
DELIMITER //
CREATE PROCEDURE database_Sensor1.MYLOOP()
BEGIN
DECLARE i int;
DECLARE str varchar(255);
SET i = 0;
WHILE i < 32 DO
SET str = CONCAT('col_',i);
SET #sql = CONCAT('ALTER TABLE database_Sensor1.persons ADD ',str,' float;');
SET i = i + 1;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END WHILE;
END
//
DELIMITER ;
CALL MYLOOP();
Editions:
IF database_name EXISTS construction not exists. Removed. See edition 3.
Procedure creation code is not finalized with delimiter. Added.
The database in which the procedure must be created is not specified explicitly. Added. If the database not exists then the error will be generated. The same with the table name.

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, ''')');

Error when calling a SP from another one

I have created the following MySQL SP successfully..
CREATE DEFINER=`root`#`%` PROCEDURE `Common_Proc_Create_NewId`
(
TableName VARCHAR(250),
ColumnName VARCHAR(150),
OUT ReturnId BIGINT
)
BEGIN
DECLARE varb BIGINT;
SET #NewId:= CONCAT('SELECT (IFNULL(MAX(', ColumnName, '), 0) + 1) INTO ', varb, ' FROM ', TableName);
PREPARE Stmnt FROM #NewId;
EXECUTE Stmnt;
DEALLOCATE PREPARE Stmnt;
SET ReturnId = varb;
END$$
But when this was called from another SP I got the following error:
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
Calling SP
CREATE DEFINER=`root`#`%` PROCEDURE `Masters_Proc_Create_BranchType`(
BranchTypName VARCHAR(100)
)
BEGIN
CALL Common_Proc_Create_NewId('Masters_BranchType', 'BranchTypeId', #Id);
INSERT INTO Masters_BranchType (BranchTypeId, BranchTypeName) VALUES (#Id, BranchTypName);
SELECT #Id;
END$$
In your stored procedure Common_Proc_Create_NewId the part into varb was causing the issue and think it's not allowed that way in a prepared statement (not sure though). Instead the way you are doing, try like below and it works fine (a sample code included)
delimiter //
CREATE PROCEDURE dynamic1(IN tbl VARCHAR(64), IN col VARCHAR(64), OUT ret int)
BEGIN
SET #s = CONCAT('SELECT #i := (IFNULL(MAX(', col, '), 0) + 1) FROM ', tbl);
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
set ret = #i;
END
//
delimiter ;
call dynamic1('test1','col',#id);
select #id;

how to set value to output parameter in dynamic sql procedure?

I have tried with following code. But it shows error msg like this undeclared variable :nt.
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_ntime`(in tb varchar(50),in d int, out nt varchar(50))
BEGIN
SET #statment = concat('Select ntime into nt from ',tb);
SET #date = CONCAT(' WHERE date = "', d, '"');
SET #statmen = CONCAT(#statment, #date);
PREPARE stmt FROM #statment;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
When used within single quotes nt will not be treated as variable but a literal.
Use local variable to set value into and assign the same to out param after execution.
Example:
DELIMITER //
CREATE DEFINER=`root`#`localhost`
PROCEDURE `get_ntime`( in tb varchar(50), in d int, out nt varchar(50) )
BEGIN
SET #staetment = concat( 'Select ntime into #nTime from ', tb );
-- SET #date = CONCAT( ' WHERE date = "', d, '"' );
SET #date = CONCAT( ' WHERE date = ?' );
SET #statement = CONCAT( #statement, #date );
SET #dt := d;
PREPARE stmt FROM #statement;
-- EXECUTE stmt;
EXECUTE stmt using #dt;
DEALLOCATE PREPARE stmt;
SET nt := #nTime;
END;
//
DELIMITER ;
Prepared statements have session scope, mysql doesn't know you want to use your prepared statement inside stored procedure only. You deallocate the statement immediately, but it doesn't have to be always like that.
Thats why mysql simply disallows using anything that has less scope inside your prepared statement - as is the case with in and out parameters, which have a scope of stored procedure.
As a workaround mentioned in mysql prepare statement manual you can use user variable inside your prepared statement and then SET your out paremeter to that user variable.

Assigning a SQL result to variable from prepared statement in MySQL

I am creating a stored procedure in MySQL and need to assign the results of a SQL query to a variable. The problem is that in order to create the SELECT statement, I have to use the CONCAT() function because I am passing in parameters.
Well it appears you can't use variables within the CONCAT function. Any ideas on how I can achieve this? The procedure I am trying to write is below:
DELIMITER //
CREATE PROCEDURE `my_proc` (IN tbl VARCHAR(20), IN col VARCHAR(20), IN id INT)
BEGIN
DECLARE #myval VARCHAR(100);
SET #t1 =CONCAT('SELECT ',col,' FROM ',tbl,' INTO #myval WHERE id = ',id );
PREPARE stmt1 FROM #t1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END //
Executing this gives me a SQL syntax error.
The problem is the following line:
...
-- SET #t1 = CONCAT('SELECT ',col,' FROM ',tbl,' INTO #myval WHERE id = ',id );
SET #t1 = CONCAT('SELECT ', col, ' INTO #myval FROM ', tbl, ' WHERE id = ', id);
...
Check the documentation: 13.2.9.1. SELECT ... INTO Syntax.
Here is a SQL Fiddle with an example.
It is important to indicate the difference between 9.4. User-Defined Variables (#t1 and #myval) and 13.6.4.1. Local Variable Syntax DECLARE (as could be: myval and t1), are different variables, therefore, it is not necessary to declare:
-- DECLARE #myval VARCHAR (100);