如何将变量传递给MySql创建过程

时间:2017-03-21 17:08:09

标签: mysql stored-procedures

我希望能够在不同的数据库中创建一些存储过程 - 所以我希望能够将数据库名称传递给存储过程创建语句。

SET @SourceDBName='dev';
DELIMITER //
CREATE PROCEDURE test ()
BEGIN 
    USE @SourceDBName;
    SELECT * FROM agreed_relation;
END //
DELIMITER ;

如何将@SourceDBName传递到CREATE PROCEDURE声明?

2 个答案:

答案 0 :(得分:1)

要将数据库名称传递到存储过程,必须在以下过程中声明它:

DELIMITER //
CREATE PROCEDURE test (IN idbname VARCHAR(20))
BEGIN 
    SELECT * FROM agreed_relation WHERE dbname = idbname;
END //
DELIMITER ;

创建像这样的表,其中' dbname'字段是您的程序将调用的字段:

create table agreed_relation
(
dbname varchar(30) not null
);

插入一些值后,调用该过程并将任何dbname传递给SELECT statament:

insert into agreed_relation(dbname) values('Oracle');
insert into agreed_relation(dbname) values('Mysql');
insert into agreed_relation(dbname) values('Mongodb');

调用程序并传递一些值:

CALL test('Mysql');

答案 1 :(得分:0)

  

14.1.16 CREATE PROCEDURE and CREATE FUNCTION Syntax

     

...

     不允许在存储例程中使用

USE语句。当一个   调用例程,执行隐式USE db_name(并撤消   当例程终止时)。导致例程具有给定的   执行时的默认数据库。对数据库中对象的引用   除了例程默认数据库之外,应该使用   适当的数据库名称。

     

...

在不同数据库中创建存储过程的选项是:

FIle:/path/to/file/myProcedure.sql

DROP PROCEDURE IF EXISTS `test`;

DELIMITER //

CREATE PROCEDURE `test`()
BEGIN 
  SELECT * FROM `agreed_relation`;
END//

DELIMITER ;

MySQL命令行:

mysql> USE `dev`;
Database changed

mysql> \. /path/to/file/myProcedure.sql
Query OK, 0 rows affected (0.00 sec)

mysql> USE `db1`;
Database changed

mysql> \. /path/to/file/myProcedure.sql
Query OK, 0 rows affected (0.00 sec)

mysql> USE `db2`;
Database changed

mysql> \. /path/to/file/myProcedure.sql
Query OK, 0 rows affected (0.00 sec)

mysql> USE `dev`;
Database changed

mysql> CALL `test`;
Empty set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

mysql> USE `db1`;
Database changed

mysql> CALL `test`;
Empty set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

mysql> USE `db2`;
Database changed

mysql> CALL `test`;
Empty set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

您还可以在单​​个数据库中创建存储过程,并将数据库名称作为参数传递给限定所需对象,并使用14.5 Prepared SQL Statement Syntax执行它:

mysql> USE `dev`;
Database changed

mysql> DROP PROCEDURE IF EXISTS `test`;
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER //

mysql> CREATE PROCEDURE `test`(`db_name` VARCHAR(64))
    -> BEGIN
    ->   SET `db_name` := TRIM('\'' FROM QUOTE(`db_name`));
    ->   SET @`query` := CONCAT('SELECT * FROM `', `db_name`, '`.`agreed_relation`');
    ->   PREPARE `stmt` FROM @`query`;
    ->   EXECUTE `stmt`;
    ->   DEALLOCATE PREPARE `stmt`;
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> CALL `test`('dev');
Empty set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

mysql> CALL `test`('db1');
Empty set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

mysql> CALL `test`('db2');
Empty set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)