MySQL Stored Procedure To Insert Test Record

Create Table

create.sql

-- ------------------------------------------------------------------------------------------------
-- Target: mariadb  Ver 15.1 Distrib 10.4.10-MariaDB, for Linux (x86_64) using readline 5.1
-- Usage: mariadb -uroot -p < ${path_to_sql}/create.sql
-- ------------------------------------------------------------------------------------------------

-- Create database --------------------------------------------------------------------------------
CREATE DATABASE `ticket` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- ------------------------------------------------------------------------------------------------

-- Create user ------------------------------------------------------------------------------------
GRANT INSERT, UPDATE, DELETE ON `ticket`.* TO `tkt`@`%` IDENTIFIED BY '1234qwer%^&*';
FLUSH PRIVILEGES;
-- ------------------------------------------------------------------------------------------------

-- Change database --------------------------------------------------------------------------------
USE `ticket`;
-- ------------------------------------------------------------------------------------------------

-- Create tables ----------------------------------------------------------------------------------
CREATE TABLE `user_info`
(
    `uuid`        CHAR(36)    NOT NULL COMMENT 'To distinguish a record',
    `user_id`     VARCHAR(16) NOT NULL COMMENT 'User id to display and search for user',
    `nickname`    VARCHAR(16) NOT NULL COMMENT 'User nickname to display',
    `gender`      TINYINT     NOT NULL DEFAULT 0 COMMENT '0 is unknown, 1 is male, 2 is female',
    `deleted`     BOOL        NOT NULL DEFAULT FALSE COMMENT 'If record had delete is true, else if false',
    `create_date` DATETIME    NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Record create datetime',
    `create_user` VARCHAR(16) NOT NULL DEFAULT 'system' COMMENT 'Record create user',
    `update_date` DATETIME    NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Record update datetime',
    `update_user` VARCHAR(16) NOT NULL DEFAULT 'system' COMMENT 'Record update user',
    PRIMARY KEY (`uuid`),
    UNIQUE KEY `user_id` (`user_id`)
);

CREATE TABLE `login_token`
(
    `uuid`          CHAR(36)    NOT NULL COMMENT 'To distinguish a record',
    `intl_tel_code` VARCHAR(3)  NOT NULL NOT NULL COMMENT 'International telephone code, use for login',
    `tel_num`       VARCHAR(11) NOT NULL COMMENT 'User telephone number, use for login',
    `password`      VARCHAR(300) NOT NULL COMMENT 'Password for login with hash',
    `user_uuid`     CHAR(36)    NOT NULL COMMENT 'Login token related user id',
    `deleted`       BOOLEAN     NOT NULL DEFAULT FALSE COMMENT 'If record had delete is true, else if false',
    `create_date`   DATETIME    NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Record create datetime',
    `create_user`   VARCHAR(16) NOT NULL DEFAULT 'system' COMMENT 'Record create user',
    `update_date`   DATETIME    NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Record update datetime',
    `update_user`   VARCHAR(16) NOT NULL DEFAULT 'system' COMMENT 'Record update user',
    PRIMARY KEY (`uuid`),
    FOREIGN KEY `user_uuid` (`user_uuid`) REFERENCES `user_info` (uuid),
    KEY `user_tel_num` (`intl_tel_code`, `tel_num`)
) ENGINE = InnoDB COMMENT 'use for user login check id and password';
-- ------------------------------------------------------------------------------------------------

Destroy Database

destroy.sql

-- ------------------------------------------------------------------------------------------------
-- Target: mariadb  Ver 15.1 Distrib 10.4.10-MariaDB, for Linux (x86_64) using readline 5.1
-- Usage: mariadb -uroot -p < ${path_to_sql}/destroy.sql
-- ------------------------------------------------------------------------------------------------

-- Drop database ----------------------------------------------------------------------------------
DROP DATABASE IF EXISTS `ticket`;
-- ------------------------------------------------------------------------------------------------

-- Drop user --------------------------------------------------------------------------------------
DROP USER IF EXISTS `tkt`@`%`;
FLUSH PRIVILEGES;
-- ------------------------------------------------------------------------------------------------

Insert Record

init.sql

-- ------------------------------------------------------------------------------------------------
-- Target: mariadb  Ver 15.1 Distrib 10.4.10-MariaDB, for Linux (x86_64) using readline 5.1
-- Usage: mariadb -uroot -p < ${path_to_sql}/init.sql
-- ------------------------------------------------------------------------------------------------

-- Change database --------------------------------------------------------------------------------
USE `ticket`;
-- ------------------------------------------------------------------------------------------------

-- User variable
-- Total user record
SET @USER_RECORD_NUM = 1000;

-- Public stored function, generate general column ------------------------------------------------
-- Generate uuid function
DELIMITER $$
CREATE FUNCTION gen_uuid() RETURNS CHAR(36)
    COMMENT 'Used for generate uuid column default value'
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
BEGIN
    DECLARE uuid CHAR(36);
    SET uuid = (SELECT UUID());
    RETURN (uuid);
END;
$$
DELIMITER ;
-- Generate deleted column function
DELIMITER $$
CREATE FUNCTION gen_deleted() RETURNS BOOLEAN
    COMMENT 'Used for generate deleted column default value'
    LANGUAGE SQL
    DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
BEGIN
    DECLARE deleted BOOLEAN;
    SET deleted = FALSE;
    RETURN (deleted);
END;
$$
DELIMITER ;
-- Generate create date column function
DELIMITER $$
CREATE FUNCTION gen_create_date() RETURNS DATETIME
    COMMENT 'Used for generate create_date column default value'
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
BEGIN
    DECLARE create_date DATETIME;
    SET create_date = (SELECT NOW());
    RETURN (create_date);
END;
$$
DELIMITER ;
-- Generate create user column function
DELIMITER $$
CREATE FUNCTION gen_create_user() RETURNS VARCHAR(16)
    COMMENT 'Used for generate create_user column default value'
    LANGUAGE SQL
    DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
BEGIN
    DECLARE create_user VARCHAR(16);
    SET create_user = 'system';
    RETURN (create_user);
END;
$$
DELIMITER ;
-- Generate update date column function
DELIMITER $$
CREATE FUNCTION gen_update_date() RETURNS DATETIME
    COMMENT 'Used for generate update_date column default value'
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
BEGIN
    DECLARE update_date DATETIME;
    SET update_date = (SELECT NOW());
    RETURN (update_date);
END;
$$
DELIMITER ;
-- Generate update user column function
DELIMITER $$
CREATE FUNCTION gen_update_user() RETURNS VARCHAR(16)
    COMMENT 'Used for generate update_user column default value'
    LANGUAGE SQL
    DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
BEGIN
    DECLARE update_user VARCHAR(16);
    SET update_user = 'system';
    RETURN (update_user);
END;
$$
DELIMITER ;
-- Generate telephone, be careful this function will return same result
DELIMITER $$
CREATE FUNCTION gen_tel_num(tel_num_length INT) RETURNS VARCHAR(11)
    COMMENT 'Generate random telephone number'
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
BEGIN
    DECLARE length_count INT DEFAULT 2;
    DECLARE tel_num VARCHAR(11) DEFAULT '1';
    -- 13xx - 19xx
    SET tel_num = CONCAT(tel_num, CAST(FLOOR((RAND() * 7) + 3) AS CHAR));
    WHILE length_count < tel_num_length
        DO
            SET length_count = length_count + 1;
            SET tel_num = CONCAT(tel_num, CAST(FLOOR((RAND() * 10)) AS CHAR));
        END WHILE;
    RETURN tel_num;
END;
$$
DELIMITER ;
-- ------------------------------------------------------------------------------------------------

-- Use stored procedure insert value --------------------------------------------------------------
-- Insert into `user_info`
DELIMITER $$
CREATE PROCEDURE init_user_info()
    COMMENT 'Insert record to init user_info'
BEGIN
    DECLARE v_uuid CHAR(36);
    DECLARE v_user_id VARCHAR(16);
    DECLARE v_nickname VARCHAR(16);
    DECLARE v_gender TINYINT;
    DECLARE v_deleted BOOLEAN;
    DECLARE v_create_date DATETIME;
    DECLARE v_create_user VARCHAR(16);
    DECLARE v_update_date DATETIME;
    DECLARE v_update_user VARCHAR(16);
    -- Use for check record unique
    DECLARE v_is_unique BIGINT;
    -- Insert count
    DECLARE v_insert_count BIGINT;
    DECLARE v_total_insert BIGINT;
    SET v_insert_count = 0;
    SELECT @USER_RECORD_NUM INTO v_total_insert;
    WHILE v_insert_count < v_total_insert
        DO
            -- Init record data
            SELECT gen_uuid() INTO v_uuid;
            SELECT CONCAT('tk_', SUBSTR(MD5(RAND()), 1, 13)) INTO v_user_id;
            SELECT SUBSTR(MD5(RAND()), 1, 7) INTO v_nickname;
            SELECT FLOOR(RAND() * 3) INTO v_gender;
            SELECT gen_deleted() INTO v_deleted;
            SELECT gen_create_date() INTO v_create_date;
            SELECT gen_create_user() INTO v_create_user;
            SELECT gen_update_date() INTO v_update_date;
            SELECT gen_update_user() INTO v_update_user;
            -- Check user_id unique
            SELECT COUNT(*) INTO v_is_unique FROM `user_info` WHERE `user_info`.`user_id` = v_user_id;
            WHILE v_is_unique > 0
                DO
                    SELECT CONCAT('tk_', SUBSTR(MD5(RAND()), 1, 13)) INTO v_user_id;
                END WHILE;
            INSERT INTO `user_info`(`uuid`, `user_id`, `nickname`, `gender`, `deleted`,
                                    `create_date`, `create_user`, `update_date`, `update_user`)
            VALUES (v_uuid, v_user_id, v_nickname, v_gender, v_deleted, v_create_date,
                    v_create_user, v_update_date, v_update_user);
            -- Output log
            SELECT CONCAT('count(s) ', (v_insert_count + 1)) AS 'Inserted into user_info: ';
            SET v_insert_count = v_insert_count + 1;
        END WHILE;
END;
$$
DELIMITER ;
-- Insert into `user_info`(`login_token` had foreign key constraint)
DELIMITER $$
CREATE PROCEDURE init_login_token()
    COMMENT 'Insert record to init user_info'
BEGIN
    DECLARE v_uuid CHAR(36);
    DECLARE v_intl_tel_code VARCHAR(3);
    DECLARE v_tel_num VARCHAR(11);
    DECLARE v_password VARCHAR(16);
    DECLARE v_user_uuid CHAR(36);
    DECLARE v_deleted BOOLEAN;
    DECLARE v_create_date DATETIME;
    DECLARE v_create_user VARCHAR(16);
    DECLARE v_update_date DATETIME;
    DECLARE v_update_user VARCHAR(16);
    -- Use cursor to read each user_info.uuid
    DECLARE v_cursor_done BOOLEAN DEFAULT FALSE;
    DECLARE v_user_info_cursor CURSOR FOR SELECT `user_info`.`uuid` FROM `user_info`;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_cursor_done = TRUE;
    OPEN v_user_info_cursor;
    user_info_loop:
    LOOP
        FETCH v_user_info_cursor INTO v_user_uuid;
        IF v_cursor_done THEN
            LEAVE user_info_loop;
        END IF;
        SELECT gen_uuid() INTO v_uuid;
        SELECT '86' INTO v_intl_tel_code;
        SELECT gen_tel_num(11) INTO v_tel_num;
        SELECT SUBSTR(SHA1(RAND()), 0) INTO v_password;
        SELECT gen_deleted() INTO v_deleted;
        SELECT gen_create_date() INTO v_create_date;
        SELECT gen_create_user() INTO v_create_user;
        SELECT gen_update_date() INTO v_update_date;
        SELECT gen_update_user() INTO v_update_user;
        INSERT INTO `login_token`(`uuid`, `intl_tel_code`, `tel_num`, `password`, `user_uuid`, `deleted`,
                                  `create_date`, `create_user`, `update_date`, `update_user`)
        VALUES (v_uuid, v_intl_tel_code, v_tel_num, v_password, v_user_uuid, v_deleted, v_create_date,
                v_create_user, v_update_date, v_update_user);
        SELECT CONCAT('user_info.user_id ', v_user_uuid) AS 'Insert into login_token: ';
    END LOOP;
    CLOSE v_user_info_cursor;
END;
$$
DELIMITER ;
-- ------------------------------------------------------------------------------------------------

-- Call procedure to init -------------------------------------------------------------------------
CALL init_user_info();
CALL init_login_token();
-- ------------------------------------------------------------------------------------------------

原文地址:https://www.cnblogs.com/seliote/p/11966394.html

时间: 2024-11-09 19:51:48

MySQL Stored Procedure To Insert Test Record的相关文章

csharp: MySQL Stored Procedure using DAL

# 建表 塗聚文 20160907 drop table attendrecord; create table attendrecord ( seq INT NOT NULL PRIMARY KEY AUTO_INCREMENT, emp_no varchar(20) null, rdate datetime not null, rtime time not null, rdescription varchar(100), rdes_reasnon varchar(100), branch va

Retrieving Out Params From a Stored Procedure With Python

http://www.rodneyoliver.com/blog/2013/08/08/retrieving-out-params-from-a-stored-procedure-with-python/ AUG 8TH, 2013 I was hacking some python today which calls a stored procedure that sends back an out parameter to indicate whether or not it complet

【机房重构】——存储过程(Stored Procedure)

[前言] 在学习数据库知识时,就曾经接触过存储过程,当时只是如蜻蜓点水一般,短暂的停留,并没有留下什么印象,在进行机房重构学习过程中,又重新认识了存储结构,从开始的抵触,不想用到后来逐渐了解,学着使用,思路越来越清晰,真正去做了才发现了其中的乐趣:常常说学习需要多总结,现在就是在积累,每一次的收获都要整理记录,才能留下深刻的印象,下面就来学习一下存储过程的知识吧. [存储过程的概念] 在采用客户机/服务器(C/S)计算模式的数据库系统中,很多工作可以在客户端完成,也可以在服务器端完成,数据库除了

EntityFramework 学习 一 Stored Procedure

CREATE PROCEDURE [dbo].[GetCoursesByStudentId] -- Add the parameters for the stored procedure here @StudentId int = null AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Inse

Publishing Stored Procedure Execution in Transactional Replication

Replication 不仅可以将Table Article 或 SP Article 推送到subscription,而且还能将sp的execution推送到subscription.推送sp的execution是指将执行sp的command 推送到subscriber去执行, 而不是将sp执行之后产生的大量transaction推送到subscriber上.Transaction是逐个更新Table Article中的数据行. 推送sp的execution来同步subscription的数据

在JDBC中传递table参数给SQL server stored procedure

SQL Server JDBC驱动不支持直接传递Table参数给stored procedure 我的做法是先创建一个临时表,将需要插入的数据先插入到临时表里面,然后把这个临时表作为参数,传送给stored procedure.使用了Preparestatement来避免SQL注入问题. 先创建User Defined Table CREATE TYPE UserIdList AS TABLE( userId uniqueidentifier NOT NULL ); 再创建存储过程: CREAT

SQL Server 在多个数据库中创建同一个存储过程(Create Same Stored Procedure in All Databases)

原文:SQL Server 在多个数据库中创建同一个存储过程(Create Same Stored Procedure in All Databases) 一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 遇到的问题(Problems) 实现代码(SQL Codes) 方法一:拼接SQL: 方法二:调用模板存储过程创建存储过程: 总结 扩展阅读 参考文献(References) 二.背景(Contexts) 在我的数据库服务器上,同一个实例

Home / Python MySQL Tutorial / Calling MySQL Stored Procedures in Python Calling MySQL Stored Procedures in Python

f you are not familiar with MySQL stored procedures or want to review it as a refresher, you can follow the MySQL stored procedures tutorial. We will create two stored procedures for the demonstration in this tutorial. The first stored procedure gets

SQL Server中存储过程Stored Procedure创建及C#调用

存储过程就是已经编译好的.优化过的放在数据库服务器中的一些SQL语句:可供应用程序直接调用.使用存储过程有以下几个优点: 1.执行速度比普通的SQL语句快 2.便于集中控制 3.可以降低网络的通信量 4.保证数据库的安全性和完整性 5.灵活性 创建存储过程 可以采用Transact-SQL语句来创建存储过程Stored Procedured.在Microsoft SQL Server Management Studio中Databases->Database Name->Programmabi