MySQL常用存储过程之新增字段
Mysql官方文档:
Add a Column to a table if not exists
MySQL allows you to create a table if it does not exist, but does not provide a native way of a adding a column (i.e. a field) to an existing table with a test of whether the column already exists - so as to avoid an error if the column already exists. The ability to add a column if it does not exist can be useful for upgrade scripts and the like.
The following script creates a stored procedure that allows a column to be added to a table but only if it does not already exist:
[code]drop procedure if exists AddColumnUnlessExists; create procedure AddColumnUnlessExists( IN dbName tinytext, IN tableName tinytext, IN fieldName tinytext, IN fieldDef text) begin IF NOT EXISTS ( SELECT * FROM information_schema.COLUMNS WHERE column_name=fieldName and table_name=tableName and table_schema=dbName ) THEN set @ddl=CONCAT('ALTER TABLE ',dbName,'.',tableName, ' ADD COLUMN ',fieldName,' ',fieldDef); prepare stmt from @ddl; execute stmt; END IF; end;
This stored procedure provides the functionality for "add column if not exists". To use the script call it with the name of the database, name of the table, name of the field and the field definition to use if the field is to be created. For example:
[code]call AddColumnUnlessExists(Database(), 'accounts', 'dob', 'varchar(32) null');
which will add the field "dob" to the table "accounts" in the current database, unless it already exists, or
[code]call AddColumnUnlessExists('GIS', 'boundaries', 'fillColour', 'int unsigned not null default 1');
which will add the field "fillColour" to the table "boundaries" in the database "GIS" if it does not already exist.
If you want to drop the stored procedure after use then use:
[code]drop procedure AddColumnUnlessExists;
- MySQL新增字段、修改字段位置和查询存储过程的SQL代码
- 转:mysql存储过程学习笔记--常用函数收藏
- mysql存储过程的创建,删除,调用及其他常用命令
- mysql存储过程repeat循环给多个表名相似的表添加相同字段
- mysql存储过程变量名与字段名重复导致查不到数据
- MySql存储过程及MySql常用流程控制语法
- mysql存储过程的创建,删除,调用及其他常用命令
- mysql存储过程的参数名不能和表字段名一样,否则不执行条件
- mysql存储过程学习笔记--常用函数
- MySql存储过程常用的函数
- mysql存储过程统计切割字符串之后的字段数
- MySQL存储过程详解 mysql 存储过程mysql存储过程详解 1. 存储过程简介 我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored
- mysql中查询表的字段名称的存储过程css('前缀','表名',1)
- mysql存储过程及常用函数
- MySQL存储过程常用的函数(字符串类型操作,数学类,日期时间类)
- MySQL存储过程详解 mysql 存储过程,if,while常用语句
- MySQL存储过程常用的函数(字符串类型操作,数学类,日期时间类)
- mysql存储过程的创建,删除,调用及其他常用命令
- [MySQL] MySQL存储过程常用的函数
- MySql存储过程及MySql常用流程控制语法