For a migration process I wanted to build in extra validation in some destructive MySQL queries, to eliminate the risk that data might be lost. Of course all data is back-upped, but I rather be safe then sorry.
This is fairly straight forward, create a stored procedure and perform an ALTER statement whenever the previously defined criteria have been met. But I wanted to define a single procedure rather then create one for every table I had to drop columns from. And since you can't simply use variables for column/table names, you have to improvise a little. I came up with the following:
-- Defining the "drop empty column" SP
DELIMITER @@
DROP PROCEDURE IF EXISTS drop_empty_column @@
CREATE PROCEDURE drop_empty_column(
IN itable VARCHAR(50),
IN icolumn VARCHAR(50),
OUT succeeded INT
)
BEGIN
SET @amount = -1;
SET @itable = itable;
SET @icolumn = icolumn;
-- Build the query, with dynamic table and column. Store the result in @amount
SELECT CONCAT('SELECT COUNT(', @icolumn ,') INTO @amount FROM ', @itable ,' WHERE(', @icolumn ,' IS NOT NULL OR ', @icolumn ,' != "");') INTO @testSql;
PREPARE testSqlStmt FROM @testSql;
-- Execute
EXECUTE testSqlStmt;
-- Check if we have 0 rows, else we still have data and we can't drop.
IF @amount = 0 THEN
-- Build the query
SELECT CONCAT('ALTER TABLE ', @itable ,' DROP COLUMN ', @icolumn ,';') INTO @alterSql;
-- Execute
PREPARE alterSqlStmt FROM @alterSql;
EXECUTE alterSqlStmt;
-- Update the status
SELECT 1 INTO succeeded;
ELSE
SELECT 0 INTO succeeded;
END IF;
END@@
DELIMITER ;
-- Conditionally drop the column "deprecated_column" from table "some_table"
CALL drop_empty_column('some_table', 'deprecated_column', @succeeded);
-- Show the status
SELECT @succeeded;
-- Cleanup
DROP PROCEDURE IF EXISTS drop_empty_column;
I'm fairly positive that this could be done in a much better way then that I'm doing here, but this works too. Simply repeat the CALL drop_empty_column(..) for every table/column combination you want to DROP and update the definition of an "empty column" to what you want. Currently it drops the column only if the values contain nothing other then NULL or "" (empty string) values.
Further reading: