Hello The following procedure will have to move all constraints from one table to the other however I am having some difficulties at the point where the constraint should be deleted.
The problem: how do I use variables in the following line
ALTER TABLE var_referenced_table_name DROP FOREIGN KEY var_constraint_name;
when I use as is, I receive the following error
Error Code: 1146. Table 'oaf_businesslink_dev.var_referenced_table_name' doesn't exist
MySQL does not recognise var_referenced_table_name and var_constraint_name as variables.
DELIMITER //
DROP PROCEDURE IF EXISTS AlterConstraints//
CREATE PROCEDURE AlterConstraints()
BEGIN
DECLARE schema_name VARCHAR(60) DEFAULT 'oaf_businesslink_dev';
DECLARE table_name VARCHAR(60) DEFAULT 'wp_systemuser';
DECLARE finished INTEGER DEFAULT 0;
DECLARE total INTEGER DEFAULT 0;
DECLARE var_constraint_name VARCHAR(60) DEFAULT '';
DECLARE var_table_name VARCHAR(60) DEFAULT '';
DECLARE var_column_name VARCHAR(60) DEFAULT '';
DECLARE var_referenced_table_name VARCHAR(60) DEFAULT '';
DECLARE var_referenced_column_name VARCHAR(60) DEFAULT '';
DECLARE cur_constraints CURSOR FOR SELECT constraint_Name, table_name,column_name,referenced_table_name,referenced_column_name
FROM information_schema.key_column_usage
WHERE constraint_schema = schema_name
AND referenced_table_name = table_name
AND table_name IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN cur_constraints;
get_constraint:
LOOP FETCH cur_constraints
INTO var_constraint_name
,var_table_name
,var_column_name
,var_referenced_table_name
,var_referenced_column_name;
IF finished THEN
LEAVE get_constraint;
END IF;
/* Get Constraint Count */
SET total = total + 1;
/* Remove Constraint */
IF EXISTS(SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = var_constraint_name AND TABLE_NAME = var_referenced_table_name AND TABLE_SCHEMA = schema_name)
THEN
/*
* Error Code: 1146. Table 'oaf_businesslink_dev.var_referenced_table_name' doesn't exist
*/
ALTER TABLE var_referenced_table_name DROP FOREIGN KEY var_constraint_name;
END IF;
/* Change Datatype to BIGINT */
/* Recreate Constraint to new table */
END
LOOP get_constraint;
CLOSE cur_constraints;
SELECT total;
END
//
DELIMITER ;
CALL AlterConstraints();
Thanks in advance.
With the use of variables as column names and tables, it would be best to DECLARE a query as a "string" and then execute that string via a Prepared Statement.
This can be done in two ways, either by CONCAT() to build the full string or by using PREPARE with arguments:
SET #query = CONCAT('ALTER TABLE ', var_referenced_table_name, ' DROP FOREIGN KEY ', var_constraint_name, ';');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Related
I have a table with design
CREATE TABLE IF NOT EXISTS InsuranceContract (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`enquiryCode` VARCHAR(20) DEFAULT NULL,
`contractCode` VARCHAR(20) DEFAULT NULL,
`createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP (),
`updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP () ON UPDATE CURRENT_TIMESTAMP (),
UNIQUE KEY (`enquiryCode`)) ENGINE=INNODB DEFAULT CHARSET=UTF8 COLLATE = UTF8_BIN;
Then I was created a procedure like this
DROP procedure IF EXISTS `sp_insurance_contract_get`;
DELIMITER $$
CREATE PROCEDURE `sp_insurance_contract_get` (enquiryCode VARCHAR(20), contractCode VARCHAR(20))
BEGIN
SET #t1 = "SELECT * FROM InsuranceContract
WHERE InsuranceContract.enquiryCode = enquiryCode
AND InsuranceContract.contractCode = contractCode;";
PREPARE param_stmt FROM #t1;
EXECUTE param_stmt;
DEALLOCATE PREPARE param_stmt;
END$$
DELIMITER ;
And I was executed this procedure in MySQL Workbench by this command:
CALL sp_insurance_contract_get('EQ000000000014', '3001002');
I expected I will receive 1 row result but it selected all records in this table.
If I copy and create exactly this #t1 into plain SQL not using statement, it's correct.
Please help me to fix this error. I'm using MySQL 8.0.19
You can use placehoders on prepare statements, this is why we use them to prevent sql injection
One other thing never use column names as variables names, databases can not differentiate
DROP procedure IF EXISTS `sp_insurance_contract_get`;
DELIMITER $$
CREATE PROCEDURE `sp_insurance_contract_get` (enquiryCode_ VARCHAR(20), contractCode_ VARCHAR(20))
BEGIN
SET #t1 = "SELECT * FROM InsuranceContract
WHERE enquiryCode = ?
AND contractCode = ?;";
PREPARE param_stmt FROM #t1;
SET #a = enquiryCode_;
SET #b = contractCode_;
EXECUTE param_stmt USING #a, #b;
DEALLOCATE PREPARE param_stmt;
END$$
DELIMITER ;
When you say
WHERE enquiryCode = enquiryCode
you compare that named column to itself. The result is true always (unless the column value is NULL).
Change the names of your SP's parameters, so you can say something like
WHERE enquiryCode_param = enquiryCode
and things should work.
Notice that you have no need of a MySql "prepared statement" here. In the MySql / MariaDb world prepared statements are used for dynamic SQL. That's for constructing statements within the server from text strings. You don't need to do that here.
I need to change a lot default values of the DB structure for new entries in MULTIPLE tables to have this new default value in DB I tried to use something like this:
SET #money_rename_def := 20*10000;
SET #money_gender_def := 40*10000;
ALTER TABLE `money` CHANGE `money_rename` `money_rename` int(10) UNSIGNED NOT NULL DEFAULT '#money_rename_def',
CHANGE `money_gender` `money_gender` int(10) UNSIGNED NOT NULL DEFAULT '#money_gender_def';
But the SET prefix does not fork for alter table command. Is there any way how to do this to use pre-defined value so I can only change it once in SET or simillar definition?
I tried to search documentation but maybe just missed it?
You can use dynamic query like this:
DROP PROCEDURE IF EXISTS `tableDefaultSetter`$$
CREATE PROCEDURE `tableDefaultSetter`()
BEGIN
SET #default1 = 20;
SET #query = concat('ALTER TABLE `ttestt` CHANGE `val` `val` int NOT NULL DEFAULT ', #default1);
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
Sample Data:
DROP TABLE IF EXISTS ttestt;
CREATE TABLE ttestt
(
id INT,
val INT(10) DEFAULT 10
);
INSERT INTO ttestt (id)
VALUES (1);
CALL tableDefaultSetter();
INSERT INTO ttestt (id)
VALUES (1);
SELECT *
FROM ttestt;
Result:
1,10
1,20
So the first item had 10 as default value and second item has been changed to 20. You see that it works.
For multiple values, you cannot put multiple queries inside one statement:
Doc
The text must represent a single statement, not multiple statements.
So you can create another procedure for convenience:
DELIMITER $$
DROP PROCEDURE IF EXISTS `exec_query`$$
CREATE PROCEDURE `exec_query`(queryStr TEXT)
BEGIN
SET #query = queryStr;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DROP PROCEDURE IF EXISTS `tableDefaultSetter`$$
CREATE PROCEDURE `tableDefaultSetter`()
BEGIN
SET #default1 = 20;
SET #default2 = 30;
SET #default3 = 40;
SET #default4 = 50;
CALL exec_query(concat('ALTER TABLE `ttestt` CHANGE `val` `val` int NOT NULL DEFAULT ', #default1));
CALL exec_query(concat('ALTER TABLE `ttestt2` CHANGE `val` `val` int NOT NULL DEFAULT ', #default2));
CALL exec_query(concat('ALTER TABLE `ttestt3` CHANGE `val` `val` int NOT NULL DEFAULT ', #default3));
CALL exec_query(concat('ALTER TABLE `ttestt4` CHANGE `val` `val` int NOT NULL DEFAULT ', #default4));
END$$
DELIMITER ;
Use it like this:
CALL tableDefaultSetter();
DROP PROCEDURE `tableDefaultSetter`;
DROP PROCEDURE `exec_query`;
I have a shared server where i have 50 to 60 databases each database has 200 tables.
How to add few new column's on all the existing databases in one go instead of one database after another manually?
ALTER TABLE `users` ADD `a` VARCHAR( 200 ) NULL;
ALTER TABLE `users` ADD `b` VARCHAR( 200 ) NULL;
ALTER TABLE `users` ADD `c` VARCHAR( 200 ) NULL;
ALTER TABLE `users` ADD `d` VARCHAR( 200 ) NULL;
ALTER TABLE `users` ADD `e` VARCHAR( 200 ) NULL;
ALTER TABLE `users` ADD `f` VARCHAR( 200 ) NULL;
You can create procedure for the same. And in procedure you can wrote cursor on this query.
select TABLE_NAME from INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='sampledata';
Make dynamic ALTER statement using Dynamic Query:
DELIMITER $$
CREATE PROCEDURE `SAMPLEPROCEDURE`(IN COLUMNNAME VARCHAR(40))
BEGIN
DECLARE VAR_TABLENAME VARCHAR(100);
DECLARE DONE INT;
DECLARE CUR CURSOR FOR
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'SAMPLEDATA';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET DONE=1;
SET DONE = 0;
OPEN CUR;
TABLELOOP: LOOP
FETCH CUR INTO VAR_TABLENAME;
IF DONE = 1 THEN LEAVE TABLELOOP; END IF;
SET #VAR_ALTER_QUERY =CONCAT("ALTER TABLE ",VAR_TABLENAME," ADD ",COLUMNNAME," VARCHAR(200) NULL");
PREPARE STMT FROM #VAR_ALTER_QUERY;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
END LOOP TABLELOOP;
END
You can took above procedure as reference for same.
use information_schema
select
case when table_schema is not null then
CONCAT("USE ",TABLE_SCHEMA) end use_schema ,
CONCAT("Alter Table '", TABLE_SCHEMA,"'.'", TABLE_NAME, " Add 'a' varchar(200)") as MySQLCMD
from TABLES
where table_name = 'USERS';
The point is that you could use the dictionary schema to retrieve each 'user' tables from each schema and generate the ALTER scripts.
Hello The following procedure will have to move all constraints from one table to the other however I am having some difficulties at the point where the constraint should be deleted.
The problem: how do I use variables in the following line
ALTER TABLE var_referenced_table_name DROP FOREIGN KEY var_constraint_name;
when I use as is, I receive the following error
Error Code: 1146. Table 'oaf_businesslink_dev.var_referenced_table_name' doesn't exist
MySQL does not recognise var_referenced_table_name and var_constraint_name as variables.
DELIMITER //
DROP PROCEDURE IF EXISTS AlterConstraints//
CREATE PROCEDURE AlterConstraints()
BEGIN
DECLARE schema_name VARCHAR(60) DEFAULT 'oaf_businesslink_dev';
DECLARE table_name VARCHAR(60) DEFAULT 'wp_systemuser';
DECLARE finished INTEGER DEFAULT 0;
DECLARE total INTEGER DEFAULT 0;
DECLARE var_constraint_name VARCHAR(60) DEFAULT '';
DECLARE var_table_name VARCHAR(60) DEFAULT '';
DECLARE var_column_name VARCHAR(60) DEFAULT '';
DECLARE var_referenced_table_name VARCHAR(60) DEFAULT '';
DECLARE var_referenced_column_name VARCHAR(60) DEFAULT '';
DECLARE cur_constraints CURSOR FOR SELECT constraint_Name, table_name,column_name,referenced_table_name,referenced_column_name
FROM information_schema.key_column_usage
WHERE constraint_schema = schema_name
AND referenced_table_name = table_name
AND table_name IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN cur_constraints;
get_constraint:
LOOP FETCH cur_constraints
INTO var_constraint_name
,var_table_name
,var_column_name
,var_referenced_table_name
,var_referenced_column_name;
IF finished THEN
LEAVE get_constraint;
END IF;
/* Get Constraint Count */
SET total = total + 1;
/* Remove Constraint */
IF EXISTS(SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = var_constraint_name AND TABLE_NAME = var_referenced_table_name AND TABLE_SCHEMA = schema_name)
THEN
/*
* Error Code: 1146. Table 'oaf_businesslink_dev.var_referenced_table_name' doesn't exist
*/
ALTER TABLE var_referenced_table_name DROP FOREIGN KEY var_constraint_name;
END IF;
/* Change Datatype to BIGINT */
/* Recreate Constraint to new table */
END
LOOP get_constraint;
CLOSE cur_constraints;
SELECT total;
END
//
DELIMITER ;
CALL AlterConstraints();
Thanks in advance.
With the use of variables as column names and tables, it would be best to DECLARE a query as a "string" and then execute that string via a Prepared Statement.
This can be done in two ways, either by CONCAT() to build the full string or by using PREPARE with arguments:
SET #query = CONCAT('ALTER TABLE ', var_referenced_table_name, ' DROP FOREIGN KEY ', var_constraint_name, ';');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I can see that there are some questions [1,2] that already ask for this, but where the solution didn't contain a complete SQL script to do this task.
I have a situation where it would be very helpful to delete all foreign keys using SQL only.
Currently I'm trying to solve this with a stored procedure and a cursor as follows:
-- No automatic commits:
DROP PROCEDURE IF EXISTS removeConstraints;
-- Magic to happen soon:
DELIMITER |
CREATE PROCEDURE removeConstraints()
BEGIN
SET AUTOCOMMIT=0;
SET FOREIGN_KEY_CHECKS=0;
-- https://dev.mysql.com/doc/refman/5.0/en/cursors.html
-- https://stackoverflow.com/questions/1745165/looping-over-result-sets-in-mysql
-- https://mariadb.com/kb/en/mariadb/cursor-overview/
DECLARE done INT DEFAULT FALSE;
DECLARE s VARCHAR(1024) DEFAULT '';
DECLARE cur CURSOR FOR SELECT CONCAT('ALTER TABLE ',TABLE_NAME, ' DROP FOREIGN KEY ', CONSTRAINT_NAME, ';')
FROM INFORMATION_SCHEMA.Key_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO s;
IF done THEN
LEAVE read_loop;
END IF;
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur;
SET FOREIGN_KEY_CHECKS=1;
COMMIT;
SET AUTOCOMMIT=1;
END |
DELIMITER ;
-- Do magic:
CALL removeConstraints();
-- Cleanup:
DROP PROCEDURE removeConstraints;
Sadly this produces the following error message:
ERROR 1064 (42000) at line 5: 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 'DECLARE done INT DEFAULT FALSE;
DECLARE s VARCHAR(1024) DEFAULT '';
DECLARE ' at line 8
With the input from Ravinder Reddy I've now updated the DECLARE parts right after the BEGIN to look like this:
CREATE PROCEDURE removeConstraints()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE s VARCHAR(1024) DEFAULT '';
DECLARE cur CURSOR FOR
SELECT DISTINCT CONCAT('ALTER TABLE ',TABLE_NAME,' DROP FOREIGN KEY ',CONSTRAINT_NAME,';')
FROM INFORMATION_SCHEMA.Key_COLUMN_USAGE
WHERE TABLE_SCHEMA=DATABASE()
AND REFERENCED_TABLE_NAME IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET AUTOCOMMIT=0;
SET FOREIGN_KEY_CHECKS=0;
but when I try to execute the procedure I still get an error:
MariaDB [v4]> CALL removeConstraints();
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
I've also tried to use a different SELECT statement like:
SELECT CONCAT('ALTER TABLE ',TABLE_NAME,' DROP FOREIGN KEY ',CONSTRAINT_NAME,';')
FROM INFORMATION_SCHEMA.Key_COLUMN_USAGE
WHERE TABLE_SCHEMA=DATABASE()
AND CONSTRAINT_NAME != 'PRIMARY'
AND CONSTRAINT_NAME IS NOT NULL
AND TABLE_NAME IS NOT NULL;
…but it didn't help.
I've got it working now by changing the code so that the CONCAT happens later.
DROP PROCEDURE IF EXISTS removeConstraints;
-- Magic to happen soon:
DELIMITER |
CREATE PROCEDURE removeConstraints()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE tName VARCHAR(64);
DECLARE cName VARCHAR(64);
DECLARE cur CURSOR FOR
SELECT DISTINCT TABLE_NAME, CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.Key_COLUMN_USAGE
WHERE TABLE_SCHEMA=DATABASE()
AND REFERENCED_TABLE_NAME IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET AUTOCOMMIT=0;
SET FOREIGN_KEY_CHECKS=0;
OPEN cur;
read_loop: LOOP
FETCH cur INTO tName, cName;
IF done THEN
LEAVE read_loop;
END IF;
SET #sql = CONCAT('ALTER TABLE ',tName,' DROP FOREIGN KEY ',cName,';');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur;
SET FOREIGN_KEY_CHECKS=1;
COMMIT;
SET AUTOCOMMIT=1;
END |
DELIMITER ;
-- Do magic:
CALL removeConstraints();
-- Cleanup:
DROP PROCEDURE removeConstraints;
All DECLARE statements must be on top in a BEGIN - END block.
And all other statements should follow them.
In your code, you have SET statements defined before DECLARE statements.
Move those statements to below of DECLARE statements.
Sample:
-- https://dev.mysql.com/doc/refman/5.0/en/cursors.html
-- https://stackoverflow.com/questions/1745165/looping-over-result-sets-in-mysql
-- https://mariadb.com/kb/en/mariadb/cursor-overview/
DECLARE done INT DEFAULT FALSE;
DECLARE s VARCHAR(1024) DEFAULT '';
DECLARE cur CURSOR FOR
SELECT CONCAT('ALTER TABLE ',TABLE_NAME,' DROP FOREIGN KEY ',CONSTRAINT_NAME,';')
FROM INFORMATION_SCHEMA.Key_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET AUTOCOMMIT=0;
SET FOREIGN_KEY_CHECKS=0;
Document Reference:
DECLARE Syntax
DECLARE is permitted only inside a BEGIN ... END compound statement
and must be at its start, before any other statements.
Declarations must follow a certain order. Cursor declarations must
appear before handler declarations. Variable and condition
declarations must appear before cursor or handler declarations