Install Stored Procedure on Multiple Databases

前端 未结 3 948
眼角桃花
眼角桃花 2021-01-22 10:38

Is there any way to easily create a stored procedure on multiple MySQL databases at once? All the databases are on the same MySQL install.

3条回答
  •  长发绾君心
    2021-01-22 11:08

    Installing in all schemas

    To get a list of the schemas, use show databases;. Combine this with -- use:

    use schemaA;
    -- use schemaB;
    -- use schemaC;
    
    create procedure ...
    

    Manually iterate through the schemas, removing and uncommenting use clauses as you move on, checking that everything works out. In MySQL Workbench, Ctrl+Shift+Enter is your friend.

    Installing routines in a subset of schemas

    Normally you don't want to install the stored routine in all schemas on a server, but only in a subset --- often defined by the set of schemas which already have some specific stored routine installed. Then, as discussed on SO, you can use a query like this to get the names of the relevant schemas:

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

    Verification

    After deploying routines, to verify the existence of them, you can use a query like this:

    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'; 
    

    This query will check whether RoutineName1, RoutineName2 and RoutineName3 exist in the database schemas on your server which have the routine FilteringRoutineName. If a routine is missing, it will be marked with ####.

    Of course, this only checks for routine existence. To verify their implementation, you may need a database diff tool (such as MySQL Compare or similar).

提交回复
热议问题