Oracle 5.0 Reference Manual page 783

Table of Contents

Advertisement

expected, or as a reserved word such as SELECT. This is true even if the variable is quoted, as shown
in the following example:
mysql>
SELECT c1 FROM t;
+----+
| c1 |
+----+
|
0 |
+----+
|
1 |
+----+
2 rows in set (0.00 sec)
mysql>
SET @col = "c1";
Query OK, 0 rows affected (0.00 sec)
mysql>
SELECT @col FROM t;
+------+
| @col |
+------+
| c1
|
+------+
1 row in set (0.00 sec)
mysql>
SELECT `@col` FROM t;
ERROR 1054 (42S22): Unknown column '@col' in 'field list'
mysql> SET @col = "`c1`";
Query OK, 0 rows affected (0.00 sec)
mysql>
SELECT @col FROM t;
+------+
| @col |
+------+
| `c1` |
+------+
1 row in set (0.00 sec)
An exception to this principle that user variables cannot be used to provide identifiers is that if you are
constructing a string for use as a prepared statement to be executed later. In this case, user variables
can be used to provide any part of the statement. The following example illustrates how this can be
done:
mysql>
SET @c = "c1";
Query OK, 0 rows affected (0.00 sec)
mysql>
SET @s = CONCAT("SELECT ", @c, " FROM t");
Query OK, 0 rows affected (0.00 sec)
mysql>
PREPARE stmt FROM @s;
Query OK, 0 rows affected (0.04 sec)
Statement prepared
mysql>
EXECUTE stmt;
+----+
| c1 |
+----+
|
0 |
+----+
|
1 |
+----+
2 rows in set (0.00 sec)
mysql>
DEALLOCATE PREPARE stmt;
Query OK, 0 rows affected (0.00 sec)
See
Section 13.5, "SQL Syntax for Prepared
A similar technique can be used in application programs to construct SQL statements using program
variables, as shown here using PHP 5:
User-Defined Variables
Statements", for more information.
763

Advertisement

Table of Contents
loading

This manual is also suitable for:

Mysql 5.0

Table of Contents