MySQL: prepared Statement in a stored Procedure - parameter error 1064 - mysql

I'm creating a sql script for a migration functionality of ours. We want to migrate data from one magento-instance to another (using pure SQL because the import/export of magento is pretty limited).
One of the challenges ist that I want to dynamically alter the AUTO_INCREMENT value of a table so it doesn't need to be done manually in multiple steps. I want to set the AUTO_INCREMENT value to the current-maximum value of the corresponding column + 1.
I prepared the following stored procedure for this:
DELIMITER $$
CREATE PROCEDURE alter_auto_inc_customer()
BEGIN
SELECT #max := MAX(entity_id)+ 1 FROM customer_entity;
PREPARE stmt FROM 'ALTER TABLE customer_entity AUTO_INCREMENT = ?';
EXECUTE stmt USING #max;
END $$
This command runs smoothly. Afterwards the procedure should just be called by a simple statement:
CALL alter_auto_inc_customer();
When I execute the "call"-statement, I get a 1064 Syntax error. It's probably trivial but I can't figure it out for the life of me...
ERROR 1064 (42000): 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 '?' at line 1
Does anyone have an idea what the issue is?
I need to get this into one or more stored procedures because I need to be able to run similar statements for multiple tables in the database.

Instead of altering the table structure you can use a trigger to get the max value + 1 before insert data:
DELIMITER $$
DROP TRIGGER IF EXISTS custom_autoincrement_bi$$
CREATE TRIGGER custom_autoincrement_bi BEFORE INSERT ON customer_entity
FOR each ROW
BEGIN
SET NEW.entity_id = select max(entity_id) + 1 from customer_entity;
END$$
DELIMITER ;
But if you want to alter the table from stored procedure
DELIMITER $$
CREATE PROCEDURE alter_auto_inc_customer()
BEGIN
SELECT MAX(entity_id) + 1 into #max FROM customer_entity;
set #sql = concat('ALTER TABLE customer_entity AUTO_INCREMENT = ', #max);
PREPARE stmt FROM #sql;
EXECUTE stmt ;
DEALLOCATE PREPARE stmt;
END $$

Related

Error Executing This Mysql Sp For Make Refresh Of The Fields Saved In Log Table Through Trigger But I Don't See The Error

This sp generate this Error but when I get the #queryString value and execute it, It's working:
Query 1 ERROR: 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 'CREATE TRIGGER triggers_after_insert AFTER INSERT ON mydb.mytable F' at line 2
This error is generated when I execute:
CALL prcTriggersLogsRefreshFields('mydb','mytable','myidtable');
This is the code:
DROP PROCEDURE "prcTriggersLogsRefreshFields";
CREATE PROCEDURE "prcTriggersLogsRefreshFields"(
par_dbName text,
par_tableName text,
par_keyField text
)
BEGIN
SET #strJsonObj = null;
SET #change_object = par_dbName||'.'||par_tableName;
SELECT GROUP_CONCAT('\'',COLUMN_NAME, '\',', COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = par_dbName AND TABLE_NAME = par_tableName INTO #strJsonObj;
SET #queryString = 'DROP TRIGGER `triggers_after_insert`;
CREATE TRIGGER `triggers_after_insert` AFTER INSERT ON `'||par_dbName||'`.`'||par_tableName||'` FOR EACH ROW BEGIN
SELECT JSON_ARRAYAGG(JSON_OBJECT('||#strJsonObj||')) change_obj FROM `'||par_dbName||'`.`'||par_tableName||'` WHERE '||par_keyField||'=New.'||par_keyField||' INTO #jsonRow;
INSERT INTO mylog_db.table_log (`change_id`, `change_date`, `db_name`, `table_name`, `change_object`, `change_event_name`, `previous_content`, `change_content`, `change_user`) VALUES (DEFAULT, NOW(), '''||par_dbName||''', '''||par_tableName||''', '''||#change_object||''', \'insert\', \'{}\', #jsonRow, New.user_created);
END;';
-- select #queryString;
PREPARE stmt FROM #queryString;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html says:
SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by ; characters).
You have to run the statements one at a time if you use PREPARE.
There's no need to include the DROP TRIGGER in your prepared statement. You can run the DROP TRIGGER without prepare & execute, since there is no dynamic part in it. Then format the CREATE TRIGGER as a single statement and prepare and execute it.

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 ;

Is it possible to copy mysql Routines to another Database using Editor

I have two databases Local and Development.
I want to move Local Db's procedures to development Db but not all. I only want newly created procedures.
For that I am writing code. But I stuck. I have definition but i don't know how to execute it on another Database using SQL Editor(Workbench/Heidi SQL).
Consider below example:
SET #Proc_new_procedure = '
DELIMITER $$
CREATE PROCEDURE `new_procedure` (input1 varchar(50),input2 varchar(50))
BEGIN
SET input1 = LTRIM(input1);
select * from table1 where column1 = input1;
select * from table2 where column1 = input2;
END$$
DELIMITER ;
';
PREPARE stmt1 FROM #Proc_new_procedure;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
I got below 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 DELIMITER $$ CREATE PROCEDURE new_procedure (input1 varchar(50),input2 varcha' at line 1
I tried Prepare statement to create procedure. But Prepare statement allow me only one statement execution at a time.
Can somebody please help me?

Mysql insert from stored procedure gives error 1064

For some strange reason, inserting from stored procedure is not working.
This is what Im trying to do:
DROP TABLE IF EXISTS test;
CREATE TABLE IF NOT EXISTS test(
id INT(9) NOT NULL AUTO_INCREMENT
,name VARCHAR(30) NOT NULL
,PRIMARY KEY (id)
) DEFAULT CHARSET=utf8;
insert into test (name) values('A');
Inserting from command line works with no problems.
Then I created a stored procedure to do the same kind of insert:
DROP PROCEDURE IF EXISTS storedtest;
DELIMITER $$
CREATE PROCEDURE storedtest()
BEGIN
declare insert_sql varchar(200);
SET insert_sql = 'insert into test (name) values(3)';
SELECT insert_sql;
PREPARE mystm FROM #insert_sql;
EXECUTE mystm;
END$$
DELIMITER ;
call storedtest();
This gives me the error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'NULL' at line 1
NULL? Where did NULL came from?
I also tried changing the sql-insert to look like this (dont know if it is a good way):
SET insert_sql = "insert into test (name) values('3')";
But mysql gives me exactly the same error.
Anyone has a clue?
The NULL MySQL is reporting is an empty user variable #insert_sql, which is different from the local stored procedure local variable insert_sql which you allocated with DECLARE.
MySQL's DECLARE is used for variables local to a stored program, but according to the documentation, PREPARE stmt FROM ... expects either a string literal or a user variable, which are the type preceded with #.
PREPARE stmt_name FROM preparable_stmt
preparable_stmt is either a string literal or a user variable that contains the text of the SQL statement.
You can allocate the untyped user variable with SET so there is no need for DECLARE. You may wish to set it to NULL when you're finished.
DROP PROCEDURE IF EXISTS storedtest;
DELIMITER $$
CREATE PROCEDURE storedtest()
BEGIN
-- Just SET the user variable
SET #insert_sql = 'insert into test (name) VALUES (3)';
SELECT #insert_sql;
-- Prepare & execute
PREPARE mystm FROM #insert_sql;
EXECUTE mystm;
-- Deallocate the statement and set the var to NULL
DEALLOCATE PREPARE mystm;
SET #insert_sql = NULL;
END$$
DELIMITER ;

MySQL ALTER TABLE with arguments in stored procedure

In a MySQL migration script, I'm trying to drop all the foreign keys of a table without knowing the name of the constraints themselves. I need this because I can only be aware of the constraints names in a particular database installation, but the script has to work also in other installations where the name is unknown at current script coding time.
Here is my first guess of a stored procedure, but it doesn't work. In particular it complains about the '?' in ALTER TABLE.
DELIMITER $$
DROP PROCEDURE IF EXISTS drop_foreign_key_documents $$
CREATE PROCEDURE drop_foreign_key_documents ( )
BEGIN
WHILE (SELECT COUNT(*) AS index_exists FROM `information_schema`.`TABLE_CONSTRAINTS` c WHERE `c`.`CONSTRAINT_TYPE` LIKE '%FOREIGN%' AND `c`.`TABLE_NAME`='documents' and `c`.`TABLE_SCHEMA`='mydb') > 0 DO
SET #ctype = '%FOREIGN%';
SET #tname = 'documents';
SET #dbname = 'mydb';
SET #n = 'select `CONSTRAINT_NAME` INTO #cname FROM `information_schema`.`TABLE_CONSTRAINTS` c WHERE `c`.`CONSTRAINT_TYPE` LIKE ? AND `c`.`TABLE_NAME`=? and `c`.`TABLE_SCHEMA`=? LIMIT 0,1';
PREPARE stmt FROM #n;
EXECUTE stmt USING #ctype,#tname,#dbname;
SELECT #cname;
SET #s = 'ALTER TABLE `documents` DROP FOREIGN KEY ?';
PREPARE stmtd FROM #s;
EXECUTE stmtd USING #cname;
END WHILE;
END $$
DELIMITER ;
CALL drop_foreign_key_documents;
The output of MySQL is:
#cname
documents_ibfk_13
ERROR 1064 (42000) at line 23: 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 '?' at line 1
Now I can imagine why it complains: the ALTER TABLE statement cannot use '?' because the constraint name is not part of a WHERE clause and so it cannot be replaced by a positional parameter. What I don't know is how to build a parametrized ALTER TABLE statement.
Obvious answer:
SET #s = CONCAT('ALTER TABLE `documents` DROP FOREIGN KEY ', #cname);
PREPARE stmtd FROM #s;
EXECUTE stmtd;