写一个mysql存储过程,循环像表内插入100个虚拟姓名和虚拟电话号 并且虚拟姓名和电话不能重复
时间: 2024-04-30 08:22:05 浏览: 47
使用存储过程实现循环插入100条记录
以下是一个示例存储过程,可以生成100个虚拟姓名和电话号码,并将其插入到指定的MySQL表中。在此示例中,我们使用了一个名为`person`的表,其中包含`id`、`name`和`phone`三个字段:
```mysql
DELIMITER //
CREATE PROCEDURE insert_fake_person()
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE j INT DEFAULT 0;
DECLARE name VARCHAR(20);
DECLARE phone VARCHAR(11);
WHILE i <= 100 DO
SET name = CONCAT('name', i);
SET phone = CONCAT('138', LPAD(j, 8, '0'));
INSERT INTO person (name, phone)
SELECT name, phone
FROM (
SELECT name, phone
FROM (
SELECT CONCAT('name', FLOOR(RAND() * 100000)) AS name,
CONCAT('138', LPAD(FLOOR(RAND() * 100000000), 8, '0')) AS phone
FROM person
WHERE name NOT IN (SELECT name FROM person) AND phone NOT IN (SELECT phone FROM person)
LIMIT 1
) AS t
UNION
SELECT name, phone
FROM (
SELECT CONCAT('name', FLOOR(RAND() * 100000)) AS name,
CONCAT('138', LPAD(FLOOR(RAND() * 100000000), 8, '0')) AS phone
FROM person
WHERE name NOT IN (SELECT name FROM person) AND phone NOT IN (SELECT phone FROM person)
LIMIT 1
) AS t2
) AS t3
LIMIT 1;
SET i = i + 1;
SET j = j + 1;
END WHILE;
END //
DELIMITER ;
```
该存储过程首先定义了一些变量,然后使用`WHILE`循环来执行100次插入操作。在每次循环中,它将生成一个随机的姓名和电话号码。如果这些随机值已经存在于表中,则会继续生成随机值,直到找到一个不存在的值。最后,它将使用`INSERT INTO ... SELECT`将这些值插入到表中。
阅读全文