MySQL SELECT存储过程的名称,并使用该名称进行调用

时间:2019-03-30 16:30:06

标签: mysql select stored-procedures call

有一个bar表,存储过程名称:

+----+------+
| id | data |
+----+------+
|  1 | one  |
|  2 | two  |
+----+------+
2 rows in set (0.00 sec)

和一个表foo,该表存储过程应在其上进行的数据:

+----+-------+
| id | data  |
+----+-------+
|  1 | three |
|  2 | four  |
+----+-------+
2 rows in set (0.00 sec)

过程one的外观如下:

DROP PROCEDURE IF EXISTS `one`;

DELIMITER $$
CREATE PROCEDURE `one`()
BEGIN
    SELECT CONCAT('Proc one: ', `data`) AS `Result`
    FROM `foo`;
END$$
DELIMITER ;

并以这种方式调用它:

CALL one();

获得预期的结果:

+-----------------+
| Result          |
+-----------------+
| Proc one: three |
| Proc one: four  |
+-----------------+
2 rows in set (0.00 sec)

过程twoone相同

DROP PROCEDURE IF EXISTS `two`;

DELIMITER $$
CREATE PROCEDURE `two`()
BEGIN
    SELECT CONCAT('Proc two: ', `data`) AS `Result` 
    FROM `foo` ;
END$$
DELIMITER ;

呼叫two也很有效:

CALL two();

结果:

+-----------------+
| Result          |
+-----------------+
| Proc two: three |
| Proc two: four  |
+-----------------+
2 rows in set (0.01 sec)

如何不通过字面名称来调用onetwo过程:

call one();
call two();

但用于存储在bar表中的名称吗?

我厌倦了使用SELECT语句代替他们的名字,但这没用。

所需的结果是调用bar中的每一行并调用foo中名称的每个过程:

+-----------------+
| Result          |
+-----------------+
| Proc one: three |
| Proc one: four  |
| Proc two: three |
| Proc two: four  |
+-----------------+

要复制表和过程,请使用以下查询:

DROP TABLE IF EXISTS `bar`;
DROP TABLE IF EXISTS `foo`;

CREATE TABLE `bar`
(
    `id` SERIAL,
    `data` TEXT NOT NULL
)
ENGINE = InnoDB;

INSERT INTO `bar` (`data`) VALUES
('one'),
('two')
;

CREATE TABLE `foo`
(
    `id` SERIAL,
    `data` TEXT NOT NULL
)
ENGINE = InnoDB;

INSERT INTO `foo` (`data`) VALUES
('three'),
('four')
;

DROP PROCEDURE IF EXISTS `one`;

DELIMITER $$
CREATE PROCEDURE `one`()
BEGIN
    SELECT CONCAT('Proc one: ', `data`) AS `Result`
    FROM `foo`;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `two`;

DELIMITER $$
CREATE PROCEDURE `two`()
BEGIN
    SELECT CONCAT('Proc two: ', `data`) AS `Result` 
    FROM `foo` ;
END$$
DELIMITER ;

CALL one();
CALL two();

我正在使用MySQL 8。

0 个答案:

没有答案