简体   繁体   中英

Check stored procedure exists or not before creating it in mysql

Requirement : Maven profile should be given a directory path, after running my maven profile all the sql files(stored procedures) in that directory should be created in my database.

Note: There is a chance of increasing in sql files in the directory, so if a new file is added, i should only run that file, instead of running all the files.

Problem: Unable to check if the procedure exists or not using IF NOT EXISTS, it is giving me syntax error when i added it in my sql file, before creating my stored procedure.

I tried using

IF NOT EXISTS(SELECT  * FROM mysql.proc WHERE name='procedure_1001') THEN
    BEGIN
        CREATE DEFINER=`root`@`localhost` PROCEDURE `procedure_1001`()
        BEGIN
        // logic
        END
    END
END IF;

Check the ROUTINES table, like this:

SELECT count(*) > 0
into @myvar 
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE 
       ROUTINE_TYPE='PROCEDURE' 
   AND ROUTINE_SCHEMA='dbname'
   AND ROUTINE_NAME = 'procedure_1001'
;

And then use @myvar later. If it is 1, then run the procedure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM