SQL Syntax for Prepared Statements
1134
SQL syntax for prepared statements is based on three SQL statements:
•
PREPARE
prepares a statement for execution (see
Section 13.5.1, “
PREPARE
Syntax”
).
•
EXECUTE
executes a prepared statement (see
Section 13.5.2, “
EXECUTE
Syntax”
).
•
DEALLOCATE PREPARE
releases a prepared statement (see
Section 13.5.3, “
DEALLOCATE
PREPARE
Syntax”
).
The following examples show two equivalent ways of preparing a statement that computes the
hypotenuse of a triangle given the lengths of the two sides.
The first example shows how to create a prepared statement by using a string literal to supply the text
of the statement:
mysql>
PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql>
SET @a = 3;
mysql>
SET @b = 4;
mysql>
EXECUTE stmt1 USING @a, @b;
+------------+
| hypotenuse |
+------------+
| 5 |
+------------+
mysql>
DEALLOCATE PREPARE stmt1;
The second example is similar, but supplies the text of the statement as a user variable:
mysql>
SET @s = 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql>
PREPARE stmt2 FROM @s;
mysql>
SET @a = 6;
mysql>
SET @b = 8;
mysql>
EXECUTE stmt2 USING @a, @b;
+------------+
| hypotenuse |
+------------+
| 10 |
+------------+
mysql>
DEALLOCATE PREPARE stmt2;
Here is an additional example which demonstrates how to choose the table on which to perform a
query at runtime, by storing the name of the table as a user variable:
mysql>
USE test;
mysql>
CREATE TABLE t1 (a INT NOT NULL);
mysql>
INSERT INTO t1 VALUES (4), (8), (11), (32), (80);
mysql>
SET @table = 't1';
mysql>
SET @s = CONCAT('SELECT * FROM ', @table);
mysql>
PREPARE stmt3 FROM @s;
mysql>
EXECUTE stmt3;
+----+
| a |
+----+
| 4 |
| 8 |
| 11 |
| 32 |
| 80 |
+----+
mysql>
DEALLOCATE PREPARE stmt3;
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.
A prepared statement is also global to the session. If you create a prepared statement within a stored
routine, it is not deallocated when the stored routine ends.
Summary of Contents for 5.0
Page 1: ...MySQL 5 0 Reference Manual ...
Page 18: ...xviii ...
Page 60: ...40 ...
Page 396: ...376 ...
Page 578: ...558 ...
Page 636: ...616 ...
Page 844: ...824 ...
Page 1234: ...1214 ...
Page 1427: ...MySQL Proxy Scripting 1407 ...
Page 1734: ...1714 ...
Page 1752: ...1732 ...
Page 1783: ...Configuring Connector ODBC 1763 ...
Page 1793: ...Connector ODBC Examples 1773 ...
Page 1839: ...Connector Net Installation 1819 2 You must choose the type of installation to perform ...
Page 2850: ...2830 ...
Page 2854: ...2834 ...
Page 2928: ...2908 ...
Page 3000: ...2980 ...
Page 3122: ...3102 ...
Page 3126: ...3106 ...
Page 3174: ...3154 ...
Page 3232: ...3212 ...