zoukankan      html  css  js  c++  java
  • MySQL 使用while语句向数据表中批量插入数据

    1.创建一张数据表

    mysql> create table test_while (
        ->   id int primary key) charset = utf8;
    Query OK, 0 rows affected (0.28 sec)

      查看数据表的结构

    mysql> desc test_while;
    +-------+---------+------+-----+---------+-------+
    | Field | Type    | Null | Key | Default | Extra |
    +-------+---------+------+-----+---------+-------+
    | id    | int(11) | NO   | PRI | NULL    |       |
    +-------+---------+------+-----+---------+-------+
    1 row in set (0.01 sec)

    2.创建存储过程,在begin..end里面写while循环以及insert语句

    mysql> delimiter #
    mysql> create procedure test_two()
        -> begin
        ->     declare i int default 0;
        ->     while i < 10 do
        ->         insert into test_while(id) values(i);
        ->         set i = i + 1;
        ->     end while;
        -> end #
    Query OK, 0 rows affected (0.00 sec)

       注释:(1)delimiter 中文意思定界符,分隔符,   在MySQL中用来设置语句的结束符。MySQL的默认结束符是 ; 设置 delimiter # 之后begin..end中以分号结束的代码

              块就不会执行啦, 然后在end后面加#结束符结束。 在创建完存储过程后用delimiter ; 恢复默认设置

               (2)declare 定义一个变量  declare int i default 0;   定义一个初始值为0的整型变量

    3.调用存储过程

    mysql> delimiter ;
    mysql> call test_two();
    Query OK, 1 row affected (0.35 sec)

    4.查看存储过程中的代码块是否调用成功了

    mysql> select * from test_while;
    +----+
    | id |
    +----+
    |  0 |
    |  1 |
    |  2 |
    |  3 |
    |  4 |
    |  5 |
    |  6 |
    |  7 |
    |  8 |
    |  9 |
    +----+
    10 rows in set (0.00 sec)
  • 相关阅读:
    centos 7遇到的问题
    Exceptions&Files
    关于Transtion属性收藏
    游戏主循环知识积累
    display:inline、block、inline-block的区别
    Sublime text 3快捷键收藏
    业务逻辑详解随记
    探究Struts2运行机制,知识积累
    将博客搬至CSDN
    url随记
  • 原文地址:https://www.cnblogs.com/shootercheng/p/6103812.html
Copyright © 2011-2022 走看看