I need to create a dynamic procedure so that whenever I need to rename a column of a table, I pass the necessary parameters, and it runs without errors. So check IF.
The error generated by this code is as follows:
You have an error in the SQL syntax; check the manual that matches your version of MySQL server for the correct syntax to use next to IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = 'People' 'on line 1
DROP PROCEDURE IF EXISTS `change_column_name`;
DELIMITER ;;
CREATE PROCEDURE `change_column_name`(IN tableName VARCHAR(100), IN columnName VARCHAR(100), IN newColumnName VARCHAR(100), IN columnType VARCHAR(20), IN defaultValue VARCHAR(100))
BEGIN
SET @query = CONCAT('IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = \'', tableName, '\' AND column_name = \'', columnName, '\') THEN
ALTER TABLE \'', tableName, '\' CHANGE COLUMN \'', columnName, '\' \'', newColumnName, '\' ', columnType, ' DEFAULT ', defaultValue, ';
END IF;');
PREPARE stmt1 FROM @query;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END ;;
DELIMITER ;
CALL `change_column_name`('People', 'Nme', 'Name', 'VARCHAR(50)', 'NULL');
source
share