Using SQL Statements Within A PL/SQL Block
Using SQL Statements Within A PL/SQL Block
Using SQL Statements Within A PL/SQL Block
5-2 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Agenda
5-3 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
SQL Statements in PL/SQL
5-4 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
SELECT Statements in PL/SQL
5-5 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
SELECT Statements in PL/SQL
5-7 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Retrieving Data in PL/SQL: Example
5-9 Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Retrieving Data in PL/SQL
Return the sum of salaries for all the employees in the specified
department.
Example:
DECLARE
v_sum_sal NUMBER(10,2);
v_deptno NUMBER NOT NULL := 60;
BEGIN
SELECT SUM(salary) -- group function
INTO v_sum_sal FROM employees
WHERE department_id = v_deptno;
DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || v_sum_sal);
END;
DECLARE
hire_date employees.hire_date%TYPE;
sysdate hire_date%TYPE;
employee_id employees.employee_id%TYPE := 176;
BEGIN
SELECT hire_date, sysdate
INTO hire_date, sysdate
FROM employees
WHERE employee_id = employee_id;
END;
/
INSERT
MERGE
UPDATE
BEGIN
INSERT INTO employees
(employee_id, first_name, last_name, email,
hire_date, job_id, salary)
VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores',
'RCORES',CURRENT_DATE, 'AD_ASST', 4000);
END;
/
...
BEGIN
MERGE INTO copy_emp c
USING employees e
ON (e.employee_id = c.empno)
WHEN MATCHED THEN
UPDATE SET
c.first_name = e.first_name,
c.last_name = e.last_name,
c.email = e.email,
. . .
WHEN NOT MATCHED THEN
INSERT VALUES(e.employee_id, e.first_name, e.last_name,
. . .,e.department_id);
END;
/
Using SQL cursor attributes, you can test the outcome of your
SQL statements.
DECLARE
v_rows_deleted VARCHAR2(30);
v_empno employees.employee_id%TYPE := 176;
BEGIN
DELETE FROM employees
WHERE employee_id = v_empno;
v_rows_deleted := (SQL%ROWCOUNT ||
' row deleted.');
DBMS_OUTPUT.PUT_LINE (v_rows_deleted);
END;