Basic Oracle Concepts and Programming Question:
Can Variables Be Used in SQL Statements?
Answer:
Yes, you can use variables in SQL statements as part of any expressions. The tutorial script provides you some good examples:
(Connect to XE with SQL*Plus)
CREATE TABLE student (id NUMBER(5) PRIMARY KEY,
first_name VARCHAR(80) NOT NULL,
last_name VARCHAR(80) NOT NULL);
Table created.
DECLARE
var_id NUMBER;
var_name CHAR(10);
BEGIN
var_id := 29;
var_name := 'Bob';
INSERT INTO student VALUES(var_id, var_name, 'Henry');
var_name := 'Joe';
INSERT INTO student VALUES(var_id+1, var_name, 'Bush');
var_name := 'ggl';
UPDATE student SET first_name = var_name
WHERE id = var_id+1;
DELETE FROM student WHERE id = var_id;
END;
/
SELECT * FROM student;
<pre>ID FIRST_NAME LAST_NAME
-------- ----------- -----------
30 ggl Bush </pre>
(Connect to XE with SQL*Plus)
CREATE TABLE student (id NUMBER(5) PRIMARY KEY,
first_name VARCHAR(80) NOT NULL,
last_name VARCHAR(80) NOT NULL);
Table created.
DECLARE
var_id NUMBER;
var_name CHAR(10);
BEGIN
var_id := 29;
var_name := 'Bob';
INSERT INTO student VALUES(var_id, var_name, 'Henry');
var_name := 'Joe';
INSERT INTO student VALUES(var_id+1, var_name, 'Bush');
var_name := 'ggl';
UPDATE student SET first_name = var_name
WHERE id = var_id+1;
DELETE FROM student WHERE id = var_id;
END;
/
SELECT * FROM student;
<pre>ID FIRST_NAME LAST_NAME
-------- ----------- -----------
30 ggl Bush </pre>
Previous Question | Next Question |
Can DDL Statements Be Used in PL/SQL? | What Happens If Variable Names Collide with Table/Column Names? |