Created
December 16, 2021 15:12
-
-
Save moeryomenko/1a5e82cec21c92e07959969b0166b0fb to your computer and use it in GitHub Desktop.
mysql5 if not exists emulation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- if not exists index | |
SET @dbname = DATABASE(); | |
SET @tablename = "TABLENAME"; | |
SET @indexname = "INDEXNAME"; | |
SET @preparedStatement = | |
(SELECT IF (EXISTS | |
(SELECT COUNT(*) | |
FROM information_schema.statistics | |
WHERE (table_schema = @dbname) | |
AND (table_name = @tablename) | |
AND (index_name = @indexname) ) > 0, | |
"SELECT 1", | |
CONCAT("ALTER TABLE ", @tablename, " ADD CONSTRAINT ", @indexname, " UNIQUE KEY(<keys...>);"))); | |
PREPARE alterIfNotExists | |
FROM @preparedStatment; | |
EXECUTE alterIfNotExists; | |
DEALLOCATE PREPARE alterIfNotExists; | |
--- if not exists column | |
SET @dbname = DATABASE(); | |
SET @tablename = "TABLENAME"; | |
SET @columnname = "COLUMNNAME"; | |
SET @preparedStatement = | |
(SELECT IF( | |
(SELECT COUNT(*) | |
FROM INFORMATION_SCHEMA.COLUMNS | |
WHERE (table_name = @tablename) | |
AND (table_schema = @dbname) | |
AND (column_name = @columnname) ) > 0, "SELECT 1", CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " text NOT NULL;"))); | |
PREPARE alterIfNotExists | |
FROM @preparedStatement; | |
EXECUTE alterIfNotExists; | |
DEALLOCATE PREPARE alterIfNotExists; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment