Skip to content

Instantly share code, notes, and snippets.

@mmuruev
Created November 5, 2019 08:06
Show Gist options
  • Save mmuruev/6bc0bd7d6dabf34dda4e51c4e156e53f to your computer and use it in GitHub Desktop.
Save mmuruev/6bc0bd7d6dabf34dda4e51c4e156e53f to your computer and use it in GitHub Desktop.
/* CREATE output SQL for safe delete TABLES FK_KEYS even if on target DB some are missing*/
SELECT
/* TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME,*/
concat(
'set @var=if((SELECT true FROM information_schema.TABLE_CONSTRAINTS WHERE
CONSTRAINT_SCHEMA = DATABASE() AND
TABLE_NAME =\'', TABLE_NAME, '\' AND
CONSTRAINT_NAME = \'', CONSTRAINT_NAME, '\' AND
CONSTRAINT_TYPE = \'FOREIGN KEY\') = true,
\'ALTER TABLE \\`', REFERENCED_TABLE_SCHEMA, '\\`.\\`', TABLE_NAME, '\\` DROP FOREIGN KEY \\`', CONSTRAINT_NAME, '\\`;\'
,\'select \'Already removed ',CONSTRAINT_NAME,'\'\');'
,'prepare stmt from @var; execute stmt; deallocate prepare stmt;') as SQL_SCRIPT
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = 'agi_platform'
AND REFERENCED_TABLE_NAME IN ('jurisdiction', 'currency', 'currency_rates', 'jurisdiction_domain', 'tax_system')
ORDER BY REFERENCED_TABLE_NAME;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment