DROP PROCEDURE IF EXISTS TRYADDTABLE;
delimiter //
CREATE PROCEDURE TRYADDTABLE (IN tableName VARCHAR(20),IN createTableSql VARCHAR(1000))
BEGIN
DECLARE tableCount INT;
SELECT COUNT(*) INTO tableCount FROM information_schema.TABLES WHERE TABLE_NAME = tableName;
IF(tableCount = 0) THEN
-- @表示全局变量 相当于php $ 拼接赋值 INTO 必须要用全局变量不然语句会报错
SET @create_sql = createTableSql;
-- 预处理需要执行的动态SQL,其中stmt是一个变量
PREPARE stmt FROM @create_sql;
-- 执行SQL语句
EXECUTE stmt;
-- 释放掉预处理段
deallocate prepare stmt;
END IF;
END //
delimiter ;
CALL TRYADDTABLE('person','CREATE TABLE person (
person_id INT NOT NULL PRIMARY KEY,
fname VARCHAR(40) NULL,
lname VARCHAR(40) NULL,
created TIMESTAMP
);');
SELECT * FROM person;
DROP PROCEDURE IF EXISTS TRYADDTABCOLUMN;
delimiter //
CREATE PROCEDURE TRYADDTABCOLUMN (IN tableName VARCHAR(50),IN colName VARCHAR(20),IN colType VARCHAR(20))
BEGIN
DECLARE colCount INT;
SELECT COUNT(*) INTO colCount FROM information_schema.COLUMNS WHERE TABLE_NAME = tableName AND COLUMN_NAME = colName;
IF(colCount = 1) THEN
-- @表示全局变量 相当于php $ 拼接赋值 INTO 必须要用全局变量不然语句会报错
SET @drop_sql = CONCAT('ALTER TABLE ',tableName,' DROP COLUMN ',colName,';');
-- 预处理需要执行的动态SQL,其中stmt是一个变量
PREPARE stmt FROM @drop_sql;
-- 执行SQL语句
EXECUTE stmt;
-- 释放掉预处理段
deallocate prepare stmt;
END IF;
-- @表示全局变量 相当于php $ 拼接赋值 INTO 必须要用全局变量不然语句会报错
SET @add_sql = CONCAT('ALTER TABLE ',tableName,' ADD COLUMN ',colName,' ',colType,';');
-- 预处理需要执行的动态SQL,其中stmt是一个变量
PREPARE stmt FROM @add_sql;
-- 执行SQL语句
EXECUTE stmt;
-- 释放掉预处理段
deallocate prepare stmt;
END //
delimiter ;
CALL TRYADDTABCOLUMN('person','fname','VARCHAR(20)');
CALL TRYADDTABCOLUMN('person','updated','TIMESTAMP');
SHOW CREATE TABLE person;