MySQL ALTER TABLE with arguments in stored procedure - mysql

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;

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.

can't create a table in mysql with dynamic sql

This is my code in MySQL.
USE database;
DROP procedure IF EXISTS CreateTable;
DELIMITER $$
USE ims_data$$
CREATE PROCEDURE CreateTable ()
BEGIN
Set #SqlQuery = Concat('DROP TABLE IF EXISTS mytemptable;');
Set #SqlQuery = Concat(#SqlQuery,'\r\n','create table mytemptable');
Set #SqlQuery = Concat(#SqlQuery,'\r\n','(');
Set #SqlQuery = Concat(#SqlQuery,'\r\n','Column1 int,');
Set #SqlQuery = Concat(#SqlQuery,'\r\n','Column2 varchar(500)');
Set #SqlQuery = Concat(#SqlQuery,'\r\n',');');
Set #SqlQuery = Concat(#SqlQuery,'\r\n','Select * from mytemptable;');
#Select #SqlQuery;
PREPARE Statement From #SqlQuery;
EXECUTE Statement;
DEALLOCATE PREPARE Statement;
END$$
DELIMITER ;
call GetUploadInformation();
I am trying to create a table but it is giving me an 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 'create table mytemptable (Stockist_Code int,Status varchar(500) ); Sele' at line 2
This is the output of query.
DROP TABLE IF EXISTS mytemptable;
create table mytemptable
(
Column1 int,
Column2 varchar(500)
);
Select * from mytemptable;
Which is working fine when executing this code withoug calling the procedure.
PREPARE/EXECUTE can only process one statement at a time. You're trying to execute two with the ;.
The error message gives you a clue in that it ran the two statements together.
You'll have to run them as separate statements.

How do you use user variables in Mysql If clause?

I want to alter a table and add a column to it if it doesn't already exist. So I populate a variable #row and if it's I want to alter the able as so.
SET #row = (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_NAME='tblname' AND COLUMN_NAME='colname' and table_schema='dbname');
IF(#row <1) THEN
ALTER TABLE tblname ADD colname INT;
END IF;
But I am getting a 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 'IF(#row <1) THEN ALTER TABLE tblname ADD colname INT' at line 1
What am I doing wrong?
In MySQL you need a shell around flow statements like if.
Put a procedure around it and it will work.
You can use prepared statements
IF (#row <1) THEN
SET #lSQL = "ALTER TABLE tblname ADD colname INT";
PREPARE stmt FROM #lSQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
Hope it helps.

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: prepared Statement in a stored Procedure - parameter error 1064

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 $$