0% found this document useful (0 votes)
263 views

(M11-MAIN) - Writing Executable Statements

The document provides information on writing executable statements in PL/SQL. It discusses variables, data types, declaring and initializing variables, implicit and explicit conversions, nested blocks, and using sequences. Variables are used for temporary storage, manipulation of stored values, and reusability. Variables must follow naming conventions and be declared with a data type. Implicit conversions occur automatically while explicit conversions require functions like TO_DATE. Nested blocks allow blocks of code to be contained within other blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
263 views

(M11-MAIN) - Writing Executable Statements

The document provides information on writing executable statements in PL/SQL. It discusses variables, data types, declaring and initializing variables, implicit and explicit conversions, nested blocks, and using sequences. Variables are used for temporary storage, manipulation of stored values, and reusability. Variables must follow naming conventions and be declared with a data type. Implicit conversions occur automatically while explicit conversions require functions like TO_DATE. Nested blocks allow blocks of code to be contained within other blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

INFORMATION MANAGEMENT

MODULE 11: Writing Executable Statements


MODULE 11

WRITING EXECUTABLE
STATEMENTS
MODULE 11

OBJECTIVES

■At the end of the chapter, the learner should be able to:
• Recognize valid and invalid identifiers
• List the uses of variables
• Declare and initialize variables
• List and describe various data types
• Identify the benefits of using the %TYPE attribute
• Declare, use, and print bind variables
MODULE 11

OBJECTIVES

■At the end of the chapter, the learner should be able to:
• Identify lexical units in a PL/SQL block
• Use built-in SQL functions in PL/SQL
• Describe when implicit conversions take place and when explicit
conversions have to be dealt with
• Write nested blocks and qualify variables with labels
• Write readable code with appropriate indentation
• Use sequences in PL/SQL expressions
Variables can be used for:
• Temporary storage of data
• Manipulation of stored values
• Reusability

SELECT
first_name,
department_id
INTO Jennifer v_fname
v_fname,
v_deptno
FROM …
10 v_deptno
A variable name:
• Must start with a letter
• Can include letters or numbers
• Can include special characters (such as $, _, and # )
• Must contain no more than 30 characters
• Must not include reserved words
Variables are:
• Declared and initialized in the declarative section
• Used and assigned new values in the executable section
• Passed as parameters to PL/SQL subprograms
• Used to hold the output of a PL/SQL subprogram
Syntax:
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];

Examples:

DECLARE
v_hiredate DATE;
v_deptno NUMBER(2) NOT NULL := 10;
v_location VARCHAR2(13) := 'Atlanta';
c_comm CONSTANT NUMBER := 1400;
DECLARE
v_myName VARCHAR2(20);
1 BEGIN
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
v_myName := 'John';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
/

DECLARE
v_myName VARCHAR2(20):= 'John';
2 BEGIN
v_myName := 'Steven';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
/
DECLARE
v_event VARCHAR2(15);
BEGIN
v_event := q'!Father's day!';
DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is :
'|| v_event );
v_event := q'[Mother's day]';
DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is :
'|| v_event );
END;
/
• PL/SQL variables:
• Scalar
• Composite
• Reference
• Large object (LOB)
• Non-PL/SQL variables: Bind variables
25-JAN-01
TRUE
Snow White
Long, long ago,
in a land far, far away,
there lived a princess called
Snow White. . .

256120.08 Atlanta
• Follow naming conventions.
• Use meaningful identifiers for variables.
• Initialize variables designated as NOT NULL and
CONSTANT.
• Initialize variables with the assignment operator (:=) or
the DEFAULT keyword:

v_myName VARCHAR2(20):='John';
v_myName VARCHAR2(20) DEFAULT 'John';

• Declare one identifier per line for better readability and


code maintenance.
• Avoid using column names as identifiers.

DECLARE
employee_id NUMBER(6);
BEGIN
SELECT employee_id
INTO employee_id
FROM employees
WHERE last_name = 'Kochhar';
END;
/

• Use the NOT NULL constraint when the variable must hold a value.
• Hold a single value
• Have no internal components

TRUE 25-JAN-01

The soul of the lazy man


desires, and he has nothing;
but the soul of the diligent
shall be made rich.

256120.08 Atlanta
• CHAR [(maximum_length)]
• VARCHAR2 (maximum_length)
• NUMBER [(precision, scale)]
• BINARY_INTEGER
• PLS_INTEGER
• BOOLEAN
• BINARY_FLOAT
• BINARY_DOUBLE
• DATE
• TIMESTAMP
• TIMESTAMP WITH TIME ZONE
• TIMESTAMP WITH LOCAL TIME ZONE
• INTERVAL YEAR TO MONTH
• INTERVAL DAY TO SECOND
Examples:
DECLARE
v_emp_job VARCHAR2(9);
v_count_loop BINARY_INTEGER := 0;
v_dept_total_sal NUMBER(9,2) := 0;
v_orderdate DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
...
• Is used to declare a variable according to:
• A database column definition
• Another declared variable
• Is prefixed with:
• The database table and column names
• The name of the declared variable
Syntax
identifier table.column_name%TYPE;

Examples
...
emp_lname employees.last_name%TYPE;
...

...
balance NUMBER(7,2);
min_balance balance%TYPE := 1000;
...
• Only the TRUE, FALSE, and NULL values can be
assigned to a Boolean variable.
• Conditional expressions use the logical operators
AND and OR and the unary operator NOT to
check the variable values.
• The variables always yield TRUE, FALSE, or
NULL.
• Arithmetic, character, and date expressions can
be used to return a Boolean value.
Bind variables are:
• Created in the environment
• Also called host variables
• Created with the VARIABLE keyword
• Used in SQL statements and PL/SQL blocks
• Accessed even after the PL/SQL block is executed
• Referenced with a preceding colon
Examples
VARIABLE b_emp_salary NUMBER
BEGIN
SELECT salary INTO :b_emp_salary
FROM employees WHERE employee_id = 178;
END;
/
PRINT b_emp_salary
SELECT first_name, last_name FROM employees
WHERE salary=:b_emp_salary;
Example
VARIABLE b_emp_salary NUMBER
SET AUTOPRINT ON
DECLARE
v_empno NUMBER(6):=&empno;
BEGIN
SELECT salary INTO :b_emp_salary
FROM employees WHERE employee_id = v_empno;
END;

Output:
7000
Book
(CLOB)

Photo
(BLOB)

Movie
(BFILE)

NCLOB
TRUE 23-DEC-98 ATLANTA

PL/SQL table structure PL/SQL table structure

1 SMITH 1 5000
2 JONES 2 2345
3 NANCY 3 12
4 TIM 4 3456

VARCHAR2 NUMBER
PLS_INTEGER PLS_INTEGER
Lexical units:
• Are building blocks of any PL/SQL block
• Are sequences of characters including letters, numerals,
tabs, spaces, returns, and symbols
• Can be classified as:
• Identifiers: v_fname, c_percent
• Delimiters: ; , +, -
• Literals: John, 428, True
• Comments: --, /* */
• Literals
• Character and date literals must be enclosed in single quotation marks.
• Numbers can be simple values or in scientific notation.

name := 'Henderson';

• Statements can span several lines.

1 2

3
• Prefix single-line comments with two hyphens (--).
• Place multiple-line comments between the symbols /* and */.
• Example:

DECLARE
...
v_annual_sal NUMBER (9,2);
BEGIN
/* Compute the annual salary based on the
monthly salary input from the user */
v_annual_sal := monthly_sal * 12;
--The following line displays the annual salary
DBMS_OUTPUT.PUT_LINE(v_annual_sal);
END;
/
• Available in procedural statements:
• Single-row functions
• Not available in procedural statements:
• DECODE
• Group functions
• Get the length of a string:
v_desc_size INTEGER(5);
v_prod_description VARCHAR2(70):='You can use this
product with your radios for higher frequency';

-- get the length of the string in prod_description


v_desc_size:= LENGTH(v_prod_description);

• Get the number of months an employee has worked:

v_tenure:= MONTHS_BETWEEN (CURRENT_DATE, v_hiredate);


Starting in 11g:
DECLARE
v_new_id NUMBER;
BEGIN
v_new_id := my_seq.NEXTVAL;
END;
/

Before 11g:
DECLARE
v_new_id NUMBER;
BEGIN
SELECT my_seq.NEXTVAL INTO v_new_id FROM Dual;
END;
/
• Converts data to comparable data types
• Is of two types:
• Implicit conversion
• Explicit conversion
• Functions:
• TO_CHAR
• TO_DATE
• TO_NUMBER
• TO_TIMESTAMP
1 date_of_joining DATE:= '02-Feb-2000';

2 date_of_joining DATE:= 'February 02,2000';

date_of_joining DATE:= TO_DATE('February


3 02,2000','Month DD, YYYY');
PL/SQL blocks can be nested.
• An executable section (BEGIN … END) can contain nested blocks.
• An exception section can contain
nested blocks.
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name);
1 DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name);
END;
2 DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
END;
/
BEGIN <<outer>>
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '
||outer.v_date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
END;
END;
END outer;
BEGIN <<outer>>
DECLARE
v_sal NUMBER(7,2) := 60000;
v_comm NUMBER(7,2) := v_sal * 0.20;
v_message VARCHAR2(255) := ' eligible for commission';
BEGIN
DECLARE
v_sal NUMBER(7,2) := 50000;
v_comm NUMBER(7,2) := 0;
v_total_comp NUMBER(7,2) := v_sal + v_comm;
BEGIN
v_message := 'CLERK not'||v_message;
1 outer.v_comm := v_sal * 0.30;
END;
v_message := 'SALESMAN'||v_message;
2 END;
END outer;
/
•Logical
•Arithmetic
•Concatenation
•Parentheses to control order
of operations

•Exponential operator (**)


• Increment the counter for a loop.

loop_count := loop_count + 1;
• Set the value of a Boolean flag.

good_sal := sal BETWEEN 50000 AND 150000;

• Validate whether an employee number contains a value.


valid := (empno IS NOT NULL);
Make code maintenance easier by:
• Documenting code with comments
• Developing a case convention for the code
• Developing naming conventions for identifiers and other objects
• Enhancing readability by indenting
For clarity, indent each level of code.
BEGIN DECLARE
IF x=0 THEN deptno NUMBER(4);
y:=1; location_id NUMBER(4);
END IF; BEGIN
END; SELECT department_id,
/ location_id
INTO deptno,
location_id
FROM departments
WHERE department_name
= 'Sales';
...
END;
/
END OF MODULE 11
• Charity Majors(2017). Database Reliability Engineering: Designing and Operating Resilient Database Systems. Canada: O'Reilly Media
• Jukic, Nenad.(2017). Database systems : introduction to databases and data warehouses. Burlington, MA: Prospect Press
• Susan Vrbsky(2016). Database Systems: Introduction to Databases and Data Warehouses. USA: Prospect Press
• Foster, Elvis C.(2016). Database systems : : a pragmatic approach. New York: Apress
• Shripad Godbole(2016). Database Systems: A Pragmatic Approach. USA: Apress
• Coronel, C. (2015). Database Systems: Design, Implementation, and Management. Australia: Cengage Learning.
• McCue, C. (2015). Data Mining and Predictive Analysis: Intelligence Gathering and Crime Analysis. Amsterdam: Elsevier.
• Wiley, J. (2015). Data science & Big Data Analytics: Discovering, Analyzing, Visualizing, & Presenting Data. Indianapolis, Indiana: John Wiley
Sons, Incorporated.
• Nong, Y. (2014). Data Mining: Theories, Algorithms, and Examples. Boca Raton: Taylor & Francis.
• Zaki, M. J. (2014). Data Mining & Analysis: Fundamental Concepts & Algorithms. New York, NY: Cambridge University Press.
• Gupta, S. (2012). Oracle Advanced PL/SQL Developer Professional Guide. Bingmingham-Mumbai: PACKT Pub.
• Serhal, L. (2009). Oracle Database 11g: Develop PL/SQL Program Units, Vol. 1 Student Guide. Oracle Acaddemy.
• Srivastava, T. (2009). Oracle Database 11g: PL/SQL Fundamentals, Student Guide. Oracle Oracle Academy.
• Price, J. (2008). Oracle Database 11g SQL: Master SQL and PL/SQL in the Oracle Database. The McGraw-Hill Companies, Inc

Introduction to Programming

You might also like