mysql alter table if exists_如果MySQL中存在列,则使用ALTER删除列

sp00m..

12

我刚刚建立了一个可重用的程序,可以帮助制作DROP COLUMN幂等法:

-- column_exists:

DROP FUNCTION IF EXISTS column_exists;

DELIMITER $$

CREATE FUNCTION column_exists(

tname VARCHAR(64),

cname VARCHAR(64)

)

RETURNS BOOLEAN

READS SQL DATA

BEGIN

RETURN 0 < (SELECT COUNT(*)

FROM `INFORMATION_SCHEMA`.`COLUMNS`

WHERE `TABLE_SCHEMA` = SCHEMA()

AND `TABLE_NAME` = tname

AND `COLUMN_NAME` = cname);

END $$

DELIMITER ;

-- drop_column_if_exists:

DROP PROCEDURE IF EXISTS drop_column_if_exists;

DELIMITER $$

CREATE PROCEDURE drop_column_if_exists(

tname VARCHAR(64),

cname VARCHAR(64)

)

BEGIN

IF column_exists(tname, cname)

THEN

SET @drop_column_if_exists = CONCAT('ALTER TABLE `', tname, '` DROP COLUMN `', cname, '`');

PREPARE drop_query FROM @drop_column_if_exists;

EXECUTE drop_query;

END IF;

END $$

DELIMITER ;

用法:

CALL drop_column_if_exists('my_table', 'my_column');

例:

SELECT column_exists('my_table', 'my_column'); -- 1

CALL drop_column_if_exists('my_table', 'my_column'); -- success

SELECT column_exists('my_table', 'my_column'); -- 0

CALL drop_column_if_exists('my_table', 'my_column'); -- success

SELECT column_exists('my_table', 'my_column'); -- 0

你可能感兴趣的:(mysql,alter,table,if,exists)