Analysis of how to create a stored procedure in MySQL to add new fields to a data table

Analysis of how to create a stored procedure in MySQL to add new fields to a data table

This article uses an example to describe how to create a stored procedure in MySQL to add new fields to a data table. Share with you for your reference, the details are as follows:

need:

Add a new field to a table in a database (if the field already exists, no operation is performed; if the field does not exist, a new field is added)

I searched Baidu for a long time, but there was no example that met the requirements. I could only refer to it and figure it out by myself. Finally, I figured it out. The following are the changes of several versions.

First Edition:

DELIMITER $$
CREATE PROCEDURE insert_column()
BEGIN
IF NOT EXISTS(SELECT 1 FROM information_schema.columns
WHERE table_schema='ltivalley' AND table_name='t_luck'
AND column_name='sss' ) THEN
alter table ltivalley.t_luck add sss varchar(255) not Null;
end if;
END
$$
DELIMITER ;

This stored procedure can add a new sss field to the t_luck table in the ltivalley database, but it is dead-coded and has no flexibility, so it is useless!

Second Edition:

DELIMITER $$
CREATE PROCEDURE insert_column(in dbname varchar(255),in tbname varchar(255),in colname varchar(255))
set @sql_1 = concat("IF NOT EXISTS(SELECT 1 FROM
information_schema.columns WHERE table_schema=",dbname,"
AND table_name=",tbname," AND column_name=",colname,")
THEN
alter table ",dbname,".",tbname," add ",colname,"
varchar(255) not null;
end if;");
PREPARE stmt FROM @sql_1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;

There is no problem in creating a stored procedure, but an error will occur when calling it, reporting an error around "IF". The reason is that in MySQL, IF can only exist in stored procedures. Using EXECUTE stmt to execute here is equivalent to not executing the if statement in the stored procedure, so an error is reported and it cannot be executed! So it’s useless!

Third Edition

DELIMITER $$
CREATE PROCEDURE insert_column(in dbname varchar(255),in tbname varchar(255),in colname varchar(255))
BEGIN
SET @selec=CONCAT('SELECT 1 FROM information_schema.columns WHERE table_schema="',dbname,'" AND table_name="',tbname,'" AND column_name="',colname,'"');
PREPARE selec FROM @selec;
SET @addcol=CONCAT('ALTER TABLE ',dbname,'.',tbname,' ADD ',colname,' VARCHAR(255)');
PREPARE addcol FROM @addcol;
IF NOT EXISTS(EXECUTE select;)THEN
EXECUTE addcol;
END IF;
END
$$
DELIMITER ;

Unable to create stored procedure because the EXECUTE select statement cannot be executed in IF NOT EXISTS() for unknown reasons. So it’s useless!

Ultimate Edition

DROP PROCEDURE IF EXISTS insert_column;
DELIMITER $$
CREATE PROCEDURE insert_column(in dbname varchar(255),in tbname varchar(255),in colname varchar(255))
BEGIN
set @iscolexists = 0;
SET @selec=CONCAT('SELECT count(*) into @iscolexists FROM information_schema.columns WHERE table_schema="',dbname,'" AND table_name="',tbname,'" AND column_name="',colname,'"');
PREPARE selec FROM @selec;
EXECUTE select;
DEALLOCATE PREPARE select;
SET @addcol=CONCAT('ALTER TABLE ',dbname,'.',tbname,' ADD ',colname,' VARCHAR(255)');
PREPARE addcol FROM @addcol;
IF(@iscolexists=0)THEN
EXECUTE addcol;
END IF;
END
$$
DELIMITER ;

For the final result, first execute EXECUTE selec and store the result in a variable @iscolexists . Then, judge the value of @iscolexists in IF() and perform corresponding operations. Available!

Readers who are interested in more MySQL-related content can check out the following topics on this site: "MySQL stored procedure skills", "MySQL common function summary", "MySQL log operation skills", "MySQL transaction operation skills summary" and "MySQL database lock related skills summary"

I hope this article will be helpful to everyone's MySQL database design.

You may also be interested in:
  • Setting the engine MyISAM/InnoDB when creating a data table in MySQL
  • Detailed explanation of creating a data table in MySQL and establishing primary and foreign key relationships
  • View, create and modify the encoding format of database and data table in MySQL
  • Detailed instructions and syntax for creating and deleting tables in MySQL
  • Create a data table instance code on Mysql
  • How to quickly create a test data table with 8 million entries in MySQL

<<:  How to run commands on a remote Linux system via SSH

>>:  A brief discussion on creating cluster in nodejs

Recommend

Detailed explanation of Linux dynamic library generation and usage guide

The file name of the dynamic library file under L...

Kill a bunch of MySQL databases with just a shell script like this (recommended)

I was woken up by a phone call early in the morni...

MySQL database optimization: index implementation principle and usage analysis

This article uses examples to illustrate the prin...

How to quickly copy large files under Linux

Copy data When copying data remotely, we usually ...

Detailed tutorial on installation and configuration of nginx under Centos7

Note: The basic directory path for software insta...

Summary of xhtml block level tags

* address - address * blockquote - block quote * c...

How to encapsulate axios in Vue project (unified management of http requests)

1. Requirements When using the Vue.js framework t...

MySQL cross-table query and cross-table update

Friends who have some basic knowledge of SQL must...

Detailed explanation of how to use Node.js to implement hot reload page

Preface Not long ago, I combined browser-sync+gul...

Detailed tutorial on installing mysql 5.7.26 on centOS7.4

MariaDB is installed by default in CentOS, which ...

HTML reuse techniques

HTML reuse is a term that is rarely mentioned. Tod...

A brief discussion on the calculation method of key_len in mysql explain

The MySQL explain command can analyze the perform...