Skip to content

Instantly share code, notes, and snippets.

@TravisBernard
Created September 4, 2020 15:14
Show Gist options
  • Save TravisBernard/e6945c639fdfae37f2c8e1e248b5139f to your computer and use it in GitHub Desktop.
Save TravisBernard/e6945c639fdfae37f2c8e1e248b5139f to your computer and use it in GitHub Desktop.
Drop FK IF EXISTS
-- Derived from https://stackoverflow.com/a/34545062/2992570
DROP PROCEDURE IF EXISTS dropForeignKeyIfExists;
delimiter ///
create procedure dropForeignKeyIfExists(IN tableName VARCHAR(64), IN constraintName VARCHAR(64))
begin
IF EXISTS(
SELECT * FROM information_schema.table_constraints
WHERE
table_schema = DATABASE() AND
table_name = tableName AND
constraint_name = constraintName AND
constraint_type = 'FOREIGN KEY')
THEN
SET @query = CONCAT('ALTER TABLE ', tableName, ' DROP FOREIGN KEY ', constraintName, ';');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
end///
delimiter ;
CALL dropForeignKeyIfExists('RMSSiteDetails', 'RMSSiteDetails_ibfk_1');
CALL dropForeignKeyIfExists('RMSDestination', 'RMSDestination_ibfk_1');
CALL dropForeignKeyIfExists('RMSRequestedOptions', 'RMSRequestedOptions_ibfk_1');
CALL dropForeignKeyIfExists('RMSCart', 'RMSCart_ibfk_1');
CALL dropForeignKeyIfExists('RMSCustomer', 'RMSCustomer_ibfk_1');
CALL dropForeignKeyIfExists('Item', 'Item_ibfk_2');
DROP PROCEDURE IF EXISTS dropForeignKeyIfExists;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment