由于业务所需,区分公司主体,tenant_id油然而生
但库里表至少几百个,不可能一个一个去加,时间成本,人力成本都很大,所以写一个存储过程函数,对其进行一次性操作
DELIMITER //
CREATE PROCEDURE AddTenantIdToTables()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE tableName VARCHAR(255);
DECLARE columnCount INT;
DECLARE cur CURSOR FOR
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'test' AND table_type = 'BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
read_loop: LOOP
FETCH cur INTO tableName;
IF done THEN
LEAVE read_loop;
END IF;
-- 检查表中是否已经存在 tenant_id 字段
SELECT COUNT(*) INTO columnCount
FROM information_schema.columns
WHERE table_schema = 'test' AND table_name = tableName AND column_name = 'tenant_id';
-- 如果表中不存在 tenant_id 字段,则执行新增字段操作
IF columnCount = 0 THEN
-- 构造 ALTER TABLE 语句为表新增字段 tenant_id
SET @alterQuery = CONCAT('ALTER TABLE ', tableName, ' ADD COLUMN tenant_id BIGINT NOT NULL DEFAULT 0;');
-- 执行 ALTER TABLE 语句
PREPARE stmt FROM @alterQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END LOOP;
CLOSE cur;
END //
DELIMITER ;
⭐️生成好该函数后,执行该函数,即可