在多个数据库上安装存储过程

时间:2011-01-21 00:54:26

标签: mysql stored-procedures

有没有办法在多个MySQL数据库上一次轻松创建存储过程?所有数据库都安装在同一个MySQL上。

3 个答案:

答案 0 :(得分:2)

在所有模式中安装

要获取模式列表,请使用show databases;。将其与-- use

结合使用
use schemaA;
-- use schemaB;
-- use schemaC;

create procedure ...

手动迭代模式,在移动时移除和取消注释use子句,检查一切是否正常。在MySQL Workbench中,Ctrl + Shift + Enter是你的朋友。

在模式子集中安装例程

通常,您不希望在服务器上的所有模式中安装存储的例程,而只是在子集中安装 - 通常由模式集定义已经安装了一些特定的存储例程。然后,as discussed on SO,您可以使用这样的查询来获取相关模式的名称:

SELECT ROUTINE_SCHEMA FROM `information_schema`.`ROUTINES` where specific_name = 'MyRoutine'; 

<强>验证

在部署例程后,为了验证它们的存在,您可以使用如下查询:

SELECT distinct
    r1.ROUTINE_SCHEMA, 
    case when r2.specific_name is not null then '' else '####' end as RoutineName1,
    case when r3.specific_name is not null then '' else '####' end as RoutineName2,
    case when r4.specific_name is not null then '' else '####' end as RoutineName3
FROM 
    `information_schema`.`ROUTINES` as r1 
LEFT JOIN (select * from `information_schema`.`ROUTINES` where specific_name = 'RoutineName1') as r2 on r1.routine_schema = r2.routine_schema
LEFT JOIN (select * from `information_schema`.`ROUTINES` where specific_name = 'RoutineName2') as r3 on r1.routine_schema = r3.routine_schema
LEFT JOIN (select * from `information_schema`.`ROUTINES` where specific_name = 'RoutineName3') as r4 on r1.routine_schema = r4.routine_schema
where 
    r1.specific_name = 'FilteringRoutineName'; 

此查询将检查服务器上具有例程RoutineName1的数据库模式中是否存在RoutineName2RoutineName3FilteringRoutineName。如果缺少例程,则会标记为####

当然,这只会检查常规存在。要验证它们的实现,您可能需要一个数据库差异工具(例如MySQL Compare或类似工具)。

答案 1 :(得分:1)

假设您使用的是Linux,那么带有模式名称数组的简单BASH循环将允许您执行此操作。

将过程定义保存到文件(例如myproc.sql),然后将该文件用作循环中mysql的输入。如果您将登录详细信息放在〜/ .my.cnf中,您还可以避免将用户名和密码放在cmdline上。

for i in dbname1 dbname2 dbname3; do mysql ${i} < myproc.sql; done;

答案 2 :(得分:0)

我建议进行复制粘贴并在每个数据库模式中创建存储过程(如果它们只需要对该模式可用)。否则,我会遵循'Kelly Vista'的建议,只是参考其中一个模式中的存储过程。