Using Variables With SQL Command Line

Previous
Previous
Next
Next

You can create queries that use variables to make SELECT statements more flexible. You can define the variable before running a SQL statement, or you specify that the statement prompts for a variable value at the time that the SQL statement is run.

When using a variable in a SQL statement, the variable name must be begin with an ampersand (&).

This section contains the following topics:

For information about using bind variables in PL/SQL code, see "Using Bind Variables With PL/SQL".

Prompting for a Variable Value in a Query

You can use & to identify a variable that you want to define dynamically. In Example: Prompting for a Variable Value in SQL Command Line, including the &employee_id variable causes the SQL statement to prompt for a value when the statement is executed. You can then enter a value for the employee_id that corresponds to the employee information that you want to display, such as employee ID 125. Note that you can use any name for the variable, such as &my_variable.

Prompting for a Variable Value in SQL Command Line

-- prompt for employee_id in a query, you need to enter a valid ID such as 125
SELECT employee_id, last_name, job_id FROM employees 
  WHERE employee_id = &employee_id;

When you run the previous SELECT statement, the output is similar to:


Enter value for employee_id: 125
...
EMPLOYEE_ID LAST_NAME                 JOB_ID
----------- ------------------------- ----------
        125 Nayer                     ST_CLERK

Reusing a Variable Value in a Query

You can use && to identify a variable that you want to define dynamically multiple times, but only want to prompt the user once. In Example: Reusing a Variable Value in SQL Command Line, including the &&column_name variable causes the SQL statement to prompt for a value when the statement is executed. The value that is entered is substituted for all remaining occurrences of &&column_name in the SQL statement.

Reusing a Variable Value in SQL Command Line

-- prompt for a column name, such as job_id, which is then substituted in the
-- remaining identical substitution variables prefixed with &&
SELECT employee_id, last_name, &&column_name FROM employees
  ORDER BY &&column_name;

Defining a Variable Value for a Query

In Example: Defining a Variable for a Query in SQL Command Line, the &job_id variable is defined before running the SQL statement with the DEFINE command, and the defined value is substituted for the variable when the statement is executed. Because the variable has already been defined, you are not prompted to enter a value.

Defining a Variable for a Query in SQL Command Line

-- define a variable value for a query as follows
DEFINE job_id = "ST_CLERK"
-- run a query using the defined value for job_id (ST_CLERK)
SELECT employee_id, last_name FROM employees WHERE job_id = '&job_id';