How do I find out if a procedure or function exists in a mysql database? and is there any discovery option? like a show procedures;
(e.g. like show tables;
)
6 Answers
A generic answer to this type of question is that all MySQL databases include a database called information_schema which includes all the metadata as tables you can just query.
The information you want is in a table called ROUTINES. For example:
SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE
ROUTINE_TYPE="PROCEDURE"
AND ROUTINE_SCHEMA="dbname"
;
-
4This also works in Oracle and SQL Server. I think its part of an ANSI standard Commented Jan 13, 2011 at 5:41
-
1Be aware that this can be affected by permissions -- you will see the list of procedures that you have access to see. This threw me off briefly when I got a partial list on one connection (using a more limited user name) and a different list on another connection. Commented May 30, 2017 at 16:07
use the following function:
DELIMITER $$
DROP FUNCTION IF EXISTS f_exists_procedure;$$
CREATE FUNCTION f_exists_procedure(in_name VARCHAR(255))
RETURNS BIT DETERMINISTIC
BEGIN
SELECT COUNT(1) INTO @f_result
FROM information_schema.ROUTINES as info
WHERE info.ROUTINE_SCHEMA = DATABASE() AND info.ROUTINE_TYPE = 'PROCEDURE' AND info.ROUTINE_NAME = in_name;
RETURN @f_result;
END;$$
DELIMITER ;
-
1
Spin Off of the answer from Gaius
SELECT IF( COUNT(*) = 0, 'F' , 'T' ) AS ProcedureExists
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = 'someDBName'
AND ROUTINE_TYPE = 'PROCEDURE'
AND UCASE(ROUTINE_NAME) = UCASE('someProcedureName');
If you just want one specific procedure:
SHOW PROCEDURE STATUS WHERE `name` = 'value'