DELIMITER //
CREATE PROCEDURE add_brand_column()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE table_name VARCHAR(255);
DECLARE alter_query VARCHAR(1000);
DECLARE cur CURSOR FOR
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'test_db';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO table_name;
IF done THEN
LEAVE read_loop;
END IF;
-- Check if column already exists in the table
IF NOT EXISTS (
SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'test_db'
AND table_name = table_name
AND column_name = 'brand'
) THEN
-- Add the column to the table
SET alter_query = CONCAT('ALTER TABLE ', table_name, ' ADD COLUMN brand VARCHAR(100)');
-- Using PREPARE and EXECUTE for dynamic SQL
PREPARE stmt FROM alter_query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END LOOP;
CLOSE cur;
END //
DELIMITER ;
此存储过程执行以下步骤:
使用游标遍历数据库中的所有表。
对于每个表,检查是否存在名为 brand 的列。
如果不存在,使用动态 SQL 添加 brand 列,类型为 VARCHAR(100)。
CALL add_brand_column();