Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to say create procedure if not exists in MySQL

I am trying to create a procedure in a MySQL database, but I want to check if it exists first.

I know how to do it for a table but when I use the same syntax for a stored procedure it doesn't compile.

Does anybody know?

like image 597
Frank Avatar asked Mar 30 '12 18:03

Frank


People also ask

How do I create a stored procedure in MySQL?

Create a simple stored procedure. DELIMITER ; To create the MySQL Stored Procedure, open the MySQL workbench Connect to the MySQL Database copy-paste the code in the query editor window click on Execute. You can view the procedure under stored procedures.

Can we write procedure in MySQL?

In the case of MySQL, procedures are written in MySQL and stored in the MySQL database/server. A MySQL procedure has a name, a parameter list, and SQL statement(s).

Can we create stored procedure without parameters?

The simplest kind of SQL Server stored procedure that you can call is one that contains no parameters and returns a single result set. The Microsoft JDBC Driver for SQL Server provides the SQLServerStatement class, which you can use to call this kind of stored procedure and process the data that it returns.


2 Answers

Just drop the procedure if it does exist and then re-add it:

DROP PROCEDURE IF EXISTS my_procedure;
CREATE PROCEDURE my_procedure()
like image 89
Cory Klein Avatar answered Oct 17 '22 11:10

Cory Klein


SELECT EXISTS(SELECT 1 FROM mysql.proc p WHERE db = 'db_name' AND name = 'stored_proc_name');

So you could do:

IF NOT EXISTS(SELECT 1 FROM mysql.proc p WHERE db = 'db_name' AND name = 'stored_proc_name') THEN
....
END IF;
like image 13
Ben English Avatar answered Oct 17 '22 10:10

Ben English