一、概述
本章节介绍使用游标来批量进行表操作,包括批量添加索引、批量添加字段等。如果对存储过程、变量定义、预处理还不是很熟悉先阅读我前面写过的关于这三个概念的文章,只有先了解了这三个概念才能更好的理解这篇文章。
理解MySQL变量和条件:http://www.bitsCN.com/article/81375.htm
理解Mysql prepare预处理语句:http://www.bitsCN.com/article/81378.htm
理解MySQL存储过程和函数:http://www.bitsCN.com/article/81381.htm
二、正文
1、声明光标
DECLARE cursor_name CURSOR FOR select_statement
这个语句声明一个光标。也可以在子程序中定义多个光标,但是一个块中的每一个光标必须有唯一的名字。
注意:SELECT语句不能有INTO子句。
2、打开光标
DECLARE cursor_name CURSOR FOR select_statement
这个语句打开先前声明的光标。
3、前进光标
FETCH cursor_name INTO var_name [, var_name] ...
这个语句用指定的打开光标读取下一行(如果有下一行的话),并且前进光标指针。
4、关闭光标
CLOSE cursor_name
这个语句关闭先前打开的光标。
5、批量添加索引
共享一个批量添加索引的游标,当一个库中有上百张表结构一样但是名称不一样的表,这个时候批量操作就变得简单了。
#删除创建存储过程 DROP PROCEDURE IF EXISTS FountTable; DELIMITER $$ CREATE PROCEDURE FountTable() BEGIN DECLARE TableName varchar(64); #声明游标 DECLARE cur_FountTable CURSOR FOR SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='front' AND TABLE_NAME LIKE 'student%'; DECLARE EXIT HANDLER FOR not found CLOSE cur_FountTable; #打开游标 OPEN cur_FountTable; REPEAT FETCH cur_FountTable INTO TableName; #定义预处理 SET @SQLSTR1 = CONCAT('create index Flag on ','`',TableName,'`',' (Flag); '); SET @SQLSTR2 = CONCAT('create index State on ','`',TableName,'`',' (State); '); SET @SQLSTR3 = CONCAT('create index upload on ','`',TableName,'`',' (upload); '); SET @SQLSTR4 = CONCAT('create index ccFlag on ','`',TableName,'`',' (lockFlag); '); SET @SQLSTR5 = CONCAT('create index comes on ','`',TableName,'`',' (comes); '); ###SET @SQLSTR=CONCAT(@SQLSTR1,@SQLSTR2,@SQLSTR3,@SQLSTR4,@SQLSTR5 ); PREPARE STMT1 FROM @SQLSTR1; PREPARE STMT2 FROM @SQLSTR2; PREPARE STMT3 FROM @SQLSTR3; PREPARE STMT4 FROM @SQLSTR4; PREPARE STMT5 FROM @SQLSTR5; EXECUTE STMT1; EXECUTE STMT2; EXECUTE STMT3; EXECUTE STMT4; EXECUTE STMT5; DEALLOCATE PREPARE STMT1; DEALLOCATE PREPARE STMT2; DEALLOCATE PREPARE STMT3; DEALLOCATE PREPARE STMT4; DEALLOCATE PREPARE STMT5; # SELECT @SQLSTR; UNTIL 0 END REPEAT; #关闭游标 CLOSE cur_FountTable; END $$ DELIMITER ; CALL FountTable();
这里有几个细节:
在声明游标的时候记得修改自己需要查询的条件
在预处理这里也需要改成对应的字段
在定义条件变量的时候这里我使用的是EXIT就是遇到错误就中断,当然也可以使用CONTINUE 。
注意:由于mysql在存储过程当中无法将查询出来的变量名直接作为表名来用,所以这里要用到动态拼接SQL的方法,但是通常的SET CONCAT的方法并不管用,所以这里就使用了PREPARE来进行预编译。
总结
批量处理虽然有时候能提高工作的效率,但是带来的潜在危险也是挺大了,所以在执行之前必须要非常有把握你执行的语句对数据的影响,否则在生成环境就非常危险了。
以上就是MySQL使用游标批量处理进行表操作_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor
