Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should prepared statements be deallocated when used inside stored procedures?

When using prepared statements inside stored procedures, should they be deallocated at the end of the procedure or not, or does it not matter, and why?

Some code to explain:

CREATE PROCEDURE getCompanyByName (IN name VARCHAR(100))
NOT DETERMINISTIC
BEGIN
  PREPARE gcbnStatement FROM 'SELECT * FROM Companies WHERE name=? LIMIT 1';
  SET @companyName = name;
  EXECUTE gcbnStatement USING @companyName;
  DEALLOCATE PREPARE gcbnStatement;
END $$

So - should the DEALLOCATE statement be there or not? Cheers!

/Victor

like image 623
Victor Avatar asked Jul 22 '09 12:07

Victor


People also ask

Can we use prepared statement for stored procedure?

We can use the prepared statements in a stored procedure by writing it inside the BEGIN and END block. We can understand it by creating an example that returns all records from a table by passing the table's name as a parameter of the stored procedure.

Should I always use prepared statements?

Prepared Statements: Why use prepared statements? There are numerous advantages to using prepared statements in your applications, both for security and performance reasons. Prepared statements can help increase security by separating SQL logic from the data being supplied.

Where are prepared statements stored?

Query result obtained by SELECT type prepared statement is stored in query cache on a universal basis independent of the source type of query and can be reused both by another execution of this or another prepared statement and by direct query when its text is identical to the SQL text of the first prepared statement.

What is deallocate prepare?

DEALLOCATE is used to deallocate a previously prepared SQL statement. If you do not explicitly deallocate a prepared statement, it is deallocated when the session ends. For more information on prepared statements, see PREPARE.


1 Answers

According to the MySQL docs:

A prepared statement is specific to the session in which it was created. If you terminate a session without deallocating a previously prepared statement, the server deallocates it automatically.

So, no, I wouldn't bother doing it explicitly, unless you have very long-running sessions.

like image 170
skaffman Avatar answered Nov 15 '22 17:11

skaffman