mysql 判断表字段或索引是否存在 - 举一反三

判断字段是否存在:

1 DROP PROCEDURE IF EXISTS schema_change;  
 2 DELIMITER //
 3 CREATE PROCEDURE schema_change() BEGIN 
 4 DECLARE  CurrentDatabase VARCHAR(100);
 5 SELECT DATABASE() INTO CurrentDatabase;
 6 IF NOT EXISTS (SELECT * FROM information_schema.columns WHERE table_schema=CurrentDatabase AND table_name = 'rtc_order' AND column_name = 'IfUpSend') THEN  
 7     ALTER TABLE rtc_order
 8     ADD COLUMN `IfUpSend` BIT  NOT NULL  DEFAULT 0 COMMENT '是否上传 是否上传';
 9 END IF;  
10 END//  
11 DELIMITER ;  
12 CALL schema_change();

判断索引是否存在:

 1 DROP PROCEDURE IF EXISTS schema_change;  
 2 DELIMITER //
 3 CREATE PROCEDURE schema_change() BEGIN 
 4 DECLARE  CurrentDatabase VARCHAR(100);
 5 SELECT DATABASE() INTO CurrentDatabase;
 6 IF NOT EXISTS (SELECT * FROM information_schema.statistics WHERE table_schema=CurrentDatabase AND table_name = 'rtc_phototype' AND index_name = 'index_name') THEN  
 7    ALTER TABLE `rtc_Phototype` ADD INDEX index_name ( `imgtype` );
 8 END IF;  
 9 END//  
10 DELIMITER ;  
11 CALL schema_change(); 

从这两段代码可以举一反三,可以得知很多信息,具体可以自己试验一下

 

posted @ 2016-06-03 11:07  hongxinerke  阅读(14120)  评论(0编辑  收藏  举报