Writing Executable Statements
-
Upload
melinda-dillon -
Category
Documents
-
view
49 -
download
0
description
Transcript of Writing Executable Statements
Writing Executable Writing Executable StatementsStatements
Writing Executable Writing Executable StatementsStatements
THE PL/SQL EXECUTION ENVIRONMENTTHE PL/SQL EXECUTION ENVIRONMENT Wherever PL/SQL technology is required (i.e. in the RDBMS core or in its tools), Wherever PL/SQL technology is required (i.e. in the RDBMS core or in its tools), the PL/SQL engine accepts any valid PL/SQL block as input.the PL/SQL engine accepts any valid PL/SQL block as input.
PL/SQL in the Oracle Engine:PL/SQL in the Oracle Engine: The PL/SQL engine resides in the Oracle engine, the Oracle engine can The PL/SQL engine resides in the Oracle engine, the Oracle engine can process not only single SQL statements but also entire PL/SQL blocks.process not only single SQL statements but also entire PL/SQL blocks.
PL/SQL block of codeDECLARE
Procedural Statements,
BEGIN
Procedural Statements,
SQL statements;
EXCEPTIONS
SQL statements;
END;
PL/SQL Engine
SQL Statement Executor
Oracle Engine
Datatype ConversionDatatype ConversionDatatype ConversionDatatype Conversion
This statement produces a compilation This statement produces a compilation error if the variable v_date is declared as error if the variable v_date is declared as datatype DATE.datatype DATE.
This statement produces a compilation This statement produces a compilation error if the variable v_date is declared as error if the variable v_date is declared as datatype DATE.datatype DATE.
v_date := 'January 13, 1998'; v_date := 'January 13, 1998';
v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY');
v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY');
To correct the error, use the TO_DATE conversion function.To correct the error, use the TO_DATE conversion function.
Datatype ConversionDatatype ConversionDatatype ConversionDatatype Conversion
Convert data to comparable datatypes.Convert data to comparable datatypes. Mixed datatypes can result in an error Mixed datatypes can result in an error
and affect performance.and affect performance. Conversion functions:Conversion functions:
• TO_CHARTO_CHAR• TO_DATETO_DATE• TO_NUMBERTO_NUMBER
Convert data to comparable datatypes.Convert data to comparable datatypes. Mixed datatypes can result in an error Mixed datatypes can result in an error
and affect performance.and affect performance. Conversion functions:Conversion functions:
• TO_CHARTO_CHAR• TO_DATETO_DATE• TO_NUMBERTO_NUMBER
DECLARE v_date VARCHAR2(15);BEGIN SELECT TO_CHAR(hiredate,
'MON. DD, YYYY') INTO v_date FROM emp WHERE empno = 7839;END;
DECLARE v_date VARCHAR2(15);BEGIN SELECT TO_CHAR(hiredate,
'MON. DD, YYYY') INTO v_date FROM emp WHERE empno = 7839;END;
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
Statements can be nested wherever an Statements can be nested wherever an executable statement is allowed.executable statement is allowed.
A nested block becomes a statement.A nested block becomes a statement. An exception section can contain nested An exception section can contain nested
blocks.blocks. The scope of an object is the region of The scope of an object is the region of
the program that can refer to the object.the program that can refer to the object.
Statements can be nested wherever an Statements can be nested wherever an executable statement is allowed.executable statement is allowed.
A nested block becomes a statement.A nested block becomes a statement. An exception section can contain nested An exception section can contain nested
blocks.blocks. The scope of an object is the region of The scope of an object is the region of
the program that can refer to the object.the program that can refer to the object.
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
Statements can be nested wherever an Statements can be nested wherever an executable statement is allowed.executable statement is allowed.
A nested block becomes a statement.A nested block becomes a statement. An exception section can contain nested An exception section can contain nested
blocks.blocks. The scope of an object is the region of The scope of an object is the region of
the program that can refer to the object.the program that can refer to the object.
Statements can be nested wherever an Statements can be nested wherever an executable statement is allowed.executable statement is allowed.
A nested block becomes a statement.A nested block becomes a statement. An exception section can contain nested An exception section can contain nested
blocks.blocks. The scope of an object is the region of The scope of an object is the region of
the program that can refer to the object.the program that can refer to the object.
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
An identifier is visible in the regions in An identifier is visible in the regions in which you can reference the which you can reference the unqualified identifier:unqualified identifier: A block can look up to the enclosing A block can look up to the enclosing
block.block. A block cannot look down to enclosed A block cannot look down to enclosed
blocks.blocks.
An identifier is visible in the regions in An identifier is visible in the regions in which you can reference the which you can reference the unqualified identifier:unqualified identifier: A block can look up to the enclosing A block can look up to the enclosing
block.block. A block cannot look down to enclosed A block cannot look down to enclosed
blocks.blocks.
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
... x BINARY_INTEGER;BEGIN ... DECLARE y NUMBER; BEGIN ... END; ...END;
Scope of x
Scope of y
ExampleExample
Operators in PL/SQLOperators in PL/SQLOperators in PL/SQLOperators in PL/SQL
LogicalLogical ArithmeticArithmetic Concatenation Concatenation Parentheses to Parentheses to
control order ofcontrol order ofoperationsoperations
Exponential operator (**)Exponential operator (**)
LogicalLogical ArithmeticArithmetic Concatenation Concatenation Parentheses to Parentheses to
control order ofcontrol order ofoperationsoperations
Exponential operator (**)Exponential operator (**)
Same as in SQL}}
ExamplesExamples Increment the index for a loop. Increment the index for a loop.
Set the value of a Boolean flag. Set the value of a Boolean flag.
Validate an employee number if it Validate an employee number if it contains a value.contains a value.
ExamplesExamples Increment the index for a loop. Increment the index for a loop.
Set the value of a Boolean flag. Set the value of a Boolean flag.
Validate an employee number if it Validate an employee number if it contains a value.contains a value.
Operators in PL/SQLOperators in PL/SQLOperators in PL/SQLOperators in PL/SQL
v_count := v_count + 1;v_count := v_count + 1;
v_equal := (v_n1 = v_n2);v_equal := (v_n1 = v_n2);
v_valid := (v_empno IS NOT NULL);v_valid := (v_empno IS NOT NULL);
Using Bind VariablesUsing Bind VariablesUsing Bind VariablesUsing Bind Variables
To reference a bind variable in PL/SQL, To reference a bind variable in PL/SQL, you must prefix its name with a colon (:).you must prefix its name with a colon (:).
ExampleExample
To reference a bind variable in PL/SQL, To reference a bind variable in PL/SQL, you must prefix its name with a colon (:).you must prefix its name with a colon (:).
ExampleExampleVARIABLE g_salary NUMBERDECLARE v_sal emp.sal%TYPE;BEGIN SELECT sal INTO v_sal FROM emp WHERE empno = 7369; :g_salary := v_sal;END;/
VARIABLE g_salary NUMBERDECLARE v_sal emp.sal%TYPE;BEGIN SELECT sal INTO v_sal FROM emp WHERE empno = 7369; :g_salary := v_sal;END;/
Code Naming ConventionsCode Naming ConventionsCode Naming ConventionsCode Naming Conventions
Avoid ambiguity:Avoid ambiguity: The names of local variables and formal The names of local variables and formal
parameters take precedence over the parameters take precedence over the names of database tables.names of database tables.
The names of columns take precedence The names of columns take precedence over the names of local variables.over the names of local variables.
Avoid ambiguity:Avoid ambiguity: The names of local variables and formal The names of local variables and formal
parameters take precedence over the parameters take precedence over the names of database tables.names of database tables.
The names of columns take precedence The names of columns take precedence over the names of local variables.over the names of local variables.
Indenting CodeIndenting CodeIndenting CodeIndenting Code
For clarity, indent each level of code.For clarity, indent each level of code. ExampleExample
For clarity, indent each level of code.For clarity, indent each level of code. ExampleExample
BEGIN IF x=0 THEN y:=1; END IF;END;
BEGIN IF x=0 THEN y:=1; END IF;END;
DECLARE v_deptno NUMBER(2); v_location VARCHAR2(13);BEGIN SELECT deptno, loc INTO v_deptno,
v_location FROM dept WHERE dname = 'SALES'; ...END;
DECLARE v_deptno NUMBER(2); v_location VARCHAR2(13);BEGIN SELECT deptno, loc INTO v_deptno,
v_location FROM dept WHERE dname = 'SALES'; ...END;
Determining Variable ScopeDetermining Variable ScopeDetermining Variable ScopeDetermining Variable Scope Class ExerciseClass Exercise Class ExerciseClass Exercise
...DECLAREV_SAL NUMBER(7,2) := 60000;V_COMM NUMBER(7,2) := V_SAL * .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; END;
V_MESSAGE := 'SALESMAN'||V_MESSAGE;END;
...DECLAREV_SAL NUMBER(7,2) := 60000;V_COMM NUMBER(7,2) := V_SAL * .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; END;
V_MESSAGE := 'SALESMAN'||V_MESSAGE;END;
Writing Control Writing Control StructuresStructures
Writing Control Writing Control StructuresStructures
Controlling PL/SQL Flow Controlling PL/SQL Flow of Executionof Execution
Controlling PL/SQL Flow Controlling PL/SQL Flow of Executionof Execution
You can change the logical flow of You can change the logical flow of statements using conditional IF statements using conditional IF statements and loop control statements and loop control structures. structures.
Conditional IFConditional IF statements: statements: IF-THEN-END IFIF-THEN-END IF IF-THEN-ELSE-END IFIF-THEN-ELSE-END IF IF-THEN-ELSIF-END IFIF-THEN-ELSIF-END IF
You can change the logical flow of You can change the logical flow of statements using conditional IF statements using conditional IF statements and loop control statements and loop control structures. structures.
Conditional IFConditional IF statements: statements: IF-THEN-END IFIF-THEN-END IF IF-THEN-ELSE-END IFIF-THEN-ELSE-END IF IF-THEN-ELSIF-END IFIF-THEN-ELSIF-END IF
IF StatementsIF StatementsIF StatementsIF Statements
IF condition THEN statements;[ELSIF condition THEN statements;][ELSE statements;]END IF;
IF condition THEN statements;[ELSIF condition THEN statements;][ELSE statements;]END IF;
SyntaxSyntax
Simple IF statement:Simple IF statement:
Set the manager ID to 22 if the employee Set the manager ID to 22 if the employee name is Osborne.name is Osborne.
SyntaxSyntax
Simple IF statement:Simple IF statement:
Set the manager ID to 22 if the employee Set the manager ID to 22 if the employee name is Osborne.name is Osborne.IF v_ename = 'OSBORNE' THEN v_mgr := 22;END IF;
IF v_ename = 'OSBORNE' THEN v_mgr := 22;END IF;
Simple IF StatementsSimple IF StatementsSimple IF StatementsSimple IF Statements
Set the job title to Salesman, the department number to 35, and the Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller.commission to 20% of the current salary if the last name is Miller.
ExampleExample
Set the job title to Salesman, the department number to 35, and the Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller.commission to 20% of the current salary if the last name is Miller.
ExampleExample
. . .IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;. . .
. . .IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;. . .
IF-THEN-ELSE Statement IF-THEN-ELSE Statement Execution FlowExecution Flow
IF-THEN-ELSE Statement IF-THEN-ELSE Statement Execution FlowExecution Flow
IF conditionIF conditionTRUETRUE
THEN actionsTHEN actions(including further IFs)(including further IFs)
THEN actionsTHEN actions(including further IFs)(including further IFs)
FALSEFALSE
ELSE actionsELSE actions(including further IFs)(including further IFs)
ELSE actionsELSE actions(including further IFs)(including further IFs)
IF-THEN-ELSE StatementsIF-THEN-ELSE StatementsIF-THEN-ELSE StatementsIF-THEN-ELSE Statements
Set a flag for orders where there are Set a flag for orders where there are fewer than five days between order fewer than five days between order date and ship date.date and ship date.
ExampleExample
Set a flag for orders where there are Set a flag for orders where there are fewer than five days between order fewer than five days between order date and ship date.date and ship date.
ExampleExample
...IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable';ELSE v_ship_flag := 'Unacceptable';END IF;...
...IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable';ELSE v_ship_flag := 'Unacceptable';END IF;...
IF-THEN-ELSIF IF-THEN-ELSIF Statement Execution FlowStatement Execution Flow
IF-THEN-ELSIF IF-THEN-ELSIF Statement Execution FlowStatement Execution Flow
IF conditionIF conditionIF conditionIF conditionTRUETRUE
THEN actionsTHEN actionsTHEN actionsTHEN actions
FALSEFALSE
ELSIFELSIFconditioncondition
ELSIFELSIFconditioncondition
TRUETRUE
THEN actionsTHEN actionsTHEN actionsTHEN actions
FALSEFALSE
ELSEELSEactionsactionsELSEELSE
actionsactions
IF-THEN-ELSIF StatementsIF-THEN-ELSIF StatementsIF-THEN-ELSIF StatementsIF-THEN-ELSIF Statements
For a given value, calculate a For a given value, calculate a percentage of that value based on a percentage of that value based on a condition.condition.
ExampleExample
For a given value, calculate a For a given value, calculate a percentage of that value based on a percentage of that value based on a condition.condition.
ExampleExample. . .IF v_start > 100 THEN v_start := 2 * v_start;ELSIF v_start >= 50 THEN v_start := .5 * v_start;ELSE v_start := .1 * v_start;END IF;. . .
. . .IF v_start > 100 THEN v_start := 2 * v_start;ELSIF v_start >= 50 THEN v_start := .5 * v_start;ELSE v_start := .1 * v_start;END IF;. . .
Building Logical ConditionsBuilding Logical ConditionsBuilding Logical ConditionsBuilding Logical Conditions
You can handle null values with the IS You can handle null values with the IS NULL operator.NULL operator.
Any arithmetic expression containing a Any arithmetic expression containing a null value evaluates to NULL.null value evaluates to NULL.
Concatenated expressions with null Concatenated expressions with null values treat null values as an empty values treat null values as an empty string.string.
You can handle null values with the IS You can handle null values with the IS NULL operator.NULL operator.
Any arithmetic expression containing a Any arithmetic expression containing a null value evaluates to NULL.null value evaluates to NULL.
Concatenated expressions with null Concatenated expressions with null values treat null values as an empty values treat null values as an empty string.string.
Logic TablesLogic TablesLogic TablesLogic Tables
Build a simple Boolean condition with Build a simple Boolean condition with a comparison operator.a comparison operator.
Build a simple Boolean condition with Build a simple Boolean condition with a comparison operator.a comparison operator.
NOT
TRUE
FALSE
NULL
OR
TRUE
FALSE
NULL
TRUE FALSE NULL
FALSE
TRUE
NULL
AND
TRUE
FALSE
NULL
TRUE FALSE NULL
TRUE
NULL NULL
NULL
FALSE FALSE
FALSE
FALSE
FALSE
TRUE
TRUE
TRUE
TRUETRUE
FALSE
NULL NULL
NULL
Iterative Control: LOOP Iterative Control: LOOP StatementsStatements
Iterative Control: LOOP Iterative Control: LOOP StatementsStatements
Loops repeat a statement or sequence Loops repeat a statement or sequence of statements multiple times.of statements multiple times.
There are three loop types:There are three loop types:• Basic loopBasic loop• FOR loopFOR loop• WHILE loopWHILE loop
Loops repeat a statement or sequence Loops repeat a statement or sequence of statements multiple times.of statements multiple times.
There are three loop types:There are three loop types:• Basic loopBasic loop• FOR loopFOR loop• WHILE loopWHILE loop
Basic LoopBasic LoopBasic LoopBasic Loop
SyntaxSyntax SyntaxSyntaxLOOP statement1; . . . EXIT [WHEN condition];END LOOP;
LOOP statement1; . . . EXIT [WHEN condition];END LOOP;
where: condition is a Boolean variable or expression (TRUE, FALSE, or NULL);
where: condition is a Boolean variable or expression (TRUE, FALSE, or NULL);
-- delimiter-- delimiter
-- statements-- statements
-- EXIT statement-- EXIT statement
-- delimiter-- delimiter
Basic LoopBasic LoopBasic LoopBasic Loop
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1;BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP;END;
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1;BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP;END;
ExampleExample ExampleExample
FOR LoopFOR LoopFOR LoopFOR Loop SyntaxSyntax
Use a FOR loop to shortcut the test for Use a FOR loop to shortcut the test for the number of iterations.the number of iterations.
Do not declare the index; it is declared Do not declare the index; it is declared implicitly.implicitly.
SyntaxSyntax
Use a FOR loop to shortcut the test for Use a FOR loop to shortcut the test for the number of iterations.the number of iterations.
Do not declare the index; it is declared Do not declare the index; it is declared implicitly.implicitly.
FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . .END LOOP;
FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . .END LOOP;
FOR LoopFOR LoopFOR LoopFOR Loop GuidelinesGuidelines
Reference the counter within the loop only; Reference the counter within the loop only; it is undefined outside the loop.it is undefined outside the loop.
Use an expression to reference the Use an expression to reference the existing value of a counter.existing value of a counter.
Do Do notnot reference the counter as the target reference the counter as the target of an assignment.of an assignment.
GuidelinesGuidelines Reference the counter within the loop only; Reference the counter within the loop only;
it is undefined outside the loop.it is undefined outside the loop. Use an expression to reference the Use an expression to reference the
existing value of a counter.existing value of a counter. Do Do notnot reference the counter as the target reference the counter as the target
of an assignment.of an assignment.
FOR LoopFOR LoopFOR LoopFOR Loop Insert the first 10 new line items for Insert the first 10 new line items for
order number 601.order number 601. ExampleExample
Insert the first 10 new line items for Insert the first 10 new line items for order number 601.order number 601.
ExampleExample
DECLARE v_ordid item.ordid%TYPE := 601;BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP;END;
DECLARE v_ordid item.ordid%TYPE := 601;BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP;END;
Nested Loops and LabelsNested Loops and LabelsNested Loops and LabelsNested Loops and Labels
...BEGIN <<Outer_loop>> LOOP v_counter := v_counter+1; EXIT WHEN v_counter>10; <<Inner_loop>> LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN inner_done = 'YES'; -- Leave inner loop only ... END LOOP Inner_loop; ... END LOOP Outer_loop;END;
...BEGIN <<Outer_loop>> LOOP v_counter := v_counter+1; EXIT WHEN v_counter>10; <<Inner_loop>> LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN inner_done = 'YES'; -- Leave inner loop only ... END LOOP Inner_loop; ... END LOOP Outer_loop;END;
Composite DatatypesComposite DatatypesComposite DatatypesComposite Datatypes
Types:Types:• PL/SQL RECORDSPL/SQL RECORDS• PL/SQL TABLESPL/SQL TABLES
Contain internal componentsContain internal components Are reusableAre reusable
Types:Types:• PL/SQL RECORDSPL/SQL RECORDS• PL/SQL TABLESPL/SQL TABLES
Contain internal componentsContain internal components Are reusableAre reusable
PL/SQL RecordsPL/SQL RecordsPL/SQL RecordsPL/SQL Records Must contain one or more components of Must contain one or more components of
any scalar, RECORD, or PL/SQL TABLE any scalar, RECORD, or PL/SQL TABLE datatype, called fieldsdatatype, called fields
Are similar in structure to records in a 3GLAre similar in structure to records in a 3GL Are not the same as rows in a database Are not the same as rows in a database
tabletable Treat a collection of fields as a logical unitTreat a collection of fields as a logical unit Are convenient for fetching a row of data Are convenient for fetching a row of data
from a table for processingfrom a table for processing
Must contain one or more components of Must contain one or more components of any scalar, RECORD, or PL/SQL TABLE any scalar, RECORD, or PL/SQL TABLE datatype, called fieldsdatatype, called fields
Are similar in structure to records in a 3GLAre similar in structure to records in a 3GL Are not the same as rows in a database Are not the same as rows in a database
tabletable Treat a collection of fields as a logical unitTreat a collection of fields as a logical unit Are convenient for fetching a row of data Are convenient for fetching a row of data
from a table for processingfrom a table for processing
Creating a PL/SQL RecordCreating a PL/SQL RecordCreating a PL/SQL RecordCreating a PL/SQL Record
SyntaxSyntax
Where Where field_declarationfield_declaration is is
SyntaxSyntax
Where Where field_declarationfield_declaration is is
TYPE type_name IS RECORD(field_declaration[, field_declaration]…);
identifier type_name;
TYPE type_name IS RECORD(field_declaration[, field_declaration]…);
identifier type_name;
field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr]
field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr]
Creating a PL/SQL RecordCreating a PL/SQL RecordCreating a PL/SQL RecordCreating a PL/SQL Record
Declare variables to store the name, job, Declare variables to store the name, job, and salary of a new employee.and salary of a new employee.
ExampleExample
Declare variables to store the name, job, Declare variables to store the name, job, and salary of a new employee.and salary of a new employee.
ExampleExample... TYPE emp_record_type IS RECORD (ename VARCHAR2(10), job VARCHAR2(9), sal NUMBER(7,2)); emp_record emp_record_type;...
... TYPE emp_record_type IS RECORD (ename VARCHAR2(10), job VARCHAR2(9), sal NUMBER(7,2)); emp_record emp_record_type;...
PL/SQL Record StructurePL/SQL Record StructurePL/SQL Record StructurePL/SQL Record Structure
Field1 (datatype)Field1 (datatype) Field2 (datatype) Field2 (datatype) Field3 (datatype) Field3 (datatype)
empno number(4) ename varchar2(10) job varchar2(9)
Field1 (datatype)Field1 (datatype) Field2 (datatype) Field2 (datatype) Field3 (datatype) Field3 (datatype)
ExampleExampleExampleExample
The %ROWTYPE AttributeThe %ROWTYPE AttributeThe %ROWTYPE AttributeThe %ROWTYPE Attribute
Declare a variable according to a Declare a variable according to a collection of columns in a database table collection of columns in a database table or view.or view.
Prefix %ROWTYPE with the database Prefix %ROWTYPE with the database table.table.
Fields in the record take their names and Fields in the record take their names and datatypes from the columns of the table datatypes from the columns of the table or view.or view.
Declare a variable according to a Declare a variable according to a collection of columns in a database table collection of columns in a database table or view.or view.
Prefix %ROWTYPE with the database Prefix %ROWTYPE with the database table.table.
Fields in the record take their names and Fields in the record take their names and datatypes from the columns of the table datatypes from the columns of the table or view.or view.
Advantages of Using Advantages of Using %ROWTYPE%ROWTYPE
Advantages of Using Advantages of Using %ROWTYPE%ROWTYPE
The number and datatypes of the The number and datatypes of the underlying database columns may not underlying database columns may not be known.be known.
The number and datatypes of the The number and datatypes of the underlying database column may underlying database column may change at runtime.change at runtime.
The attribute is useful when retrieving a The attribute is useful when retrieving a row with the SELECT statement.row with the SELECT statement.
The number and datatypes of the The number and datatypes of the underlying database columns may not underlying database columns may not be known.be known.
The number and datatypes of the The number and datatypes of the underlying database column may underlying database column may change at runtime.change at runtime.
The attribute is useful when retrieving a The attribute is useful when retrieving a row with the SELECT statement.row with the SELECT statement.
The %ROWTYPE AttributeThe %ROWTYPE AttributeThe %ROWTYPE AttributeThe %ROWTYPE Attribute
ExamplesExamples Declare a variable to store the same Declare a variable to store the same
information about a department as it information about a department as it is stored in the DEPT table. is stored in the DEPT table.
Declare a variable to store the same Declare a variable to store the same information about an employee as it is information about an employee as it is stored in the EMP table.stored in the EMP table.
ExamplesExamples Declare a variable to store the same Declare a variable to store the same
information about a department as it information about a department as it is stored in the DEPT table. is stored in the DEPT table.
Declare a variable to store the same Declare a variable to store the same information about an employee as it is information about an employee as it is stored in the EMP table.stored in the EMP table.
dept_record dept%ROWTYPE; dept_record dept%ROWTYPE;
emp_record emp%ROWTYPE; emp_record emp%ROWTYPE;
Creating a PL/SQL TableCreating a PL/SQL TableCreating a PL/SQL TableCreating a PL/SQL Table SyntaxSyntax SyntaxSyntaxTYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] [INDEX BY BINARY_INTEGER];identifier type_name;
TYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] [INDEX BY BINARY_INTEGER];identifier type_name;
...TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER;ename_table ename_table_type;...
...TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER;ename_table ename_table_type;...
ExampleExampleExampleExampleDeclare a PL/SQL variable to store a name.Declare a PL/SQL variable to store a name.Declare a PL/SQL variable to store a name.Declare a PL/SQL variable to store a name.
PL/SQL Table StructurePL/SQL Table StructurePL/SQL Table StructurePL/SQL Table Structure
Primary keyPrimary key ColumnColumn ...... ......
11 JonesJones 22 SmithSmith 33 MaduroMaduro
...... ......
BINARY_INTEGERBINARY_INTEGER ScalarScalar
Creating a PL/SQL TableCreating a PL/SQL TableCreating a PL/SQL TableCreating a PL/SQL Table
DECLARE TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; TYPE hiredate_table_type IS TABLE OF DATE INDEX BY BINARY_INTEGER; ename_table ename_table_type; hiredate_table hiredate_table_type;BEGIN ename_table(1) := 'CAMERON'; hiredate_table(8) := SYSDATE + 7; IF ename_table.EXISTS(1) THEN INSERT INTO ... ...END;
DECLARE TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; TYPE hiredate_table_type IS TABLE OF DATE INDEX BY BINARY_INTEGER; ename_table ename_table_type; hiredate_table hiredate_table_type;BEGIN ename_table(1) := 'CAMERON'; hiredate_table(8) := SYSDATE + 7; IF ename_table.EXISTS(1) THEN INSERT INTO ... ...END;
PL/SQL Table of RecordsPL/SQL Table of RecordsPL/SQL Table of RecordsPL/SQL Table of Records
• Define a TABLE variable with the %ROWTYPE attribute.
• Declare a PL/SQL variable to hold department information.
ExampleExample
• Define a TABLE variable with the %ROWTYPE attribute.
• Declare a PL/SQL variable to hold department information.
ExampleExampleDECLARE TYPE dept_table_type IS TABLE OF dept%ROWTYPE INDEX BY BINARY_INTEGER; dept_table dept_table_type; -- Each element of dept_table is a record
DECLARE TYPE dept_table_type IS TABLE OF dept%ROWTYPE INDEX BY BINARY_INTEGER; dept_table dept_table_type; -- Each element of dept_table is a record
Using PL/SQL Table MethodsUsing PL/SQL Table MethodsUsing PL/SQL Table MethodsUsing PL/SQL Table Methods
The following methods make The following methods make PL/SQL tables easier to use:PL/SQL tables easier to use: EXISTSEXISTS COUNTCOUNT FIRST and LASTFIRST and LAST PRIOR PRIOR
The following methods make The following methods make PL/SQL tables easier to use:PL/SQL tables easier to use: EXISTSEXISTS COUNTCOUNT FIRST and LASTFIRST and LAST PRIOR PRIOR
NEXTNEXT EXTENDEXTEND TRIMTRIM DELETEDELETE
NEXTNEXT EXTENDEXTEND TRIMTRIM DELETEDELETE
SummarySummarySummarySummary
Define and reference PL/SQL variables Define and reference PL/SQL variables of composite datatypes:of composite datatypes:• PL/SQL recordsPL/SQL records• PL/SQL tablesPL/SQL tables• PL/SQL table of recordsPL/SQL table of records
Define a PL/SQL record using the Define a PL/SQL record using the %ROWTYPE attribute.%ROWTYPE attribute.
Define and reference PL/SQL variables Define and reference PL/SQL variables of composite datatypes:of composite datatypes:• PL/SQL recordsPL/SQL records• PL/SQL tablesPL/SQL tables• PL/SQL table of recordsPL/SQL table of records
Define a PL/SQL record using the Define a PL/SQL record using the %ROWTYPE attribute.%ROWTYPE attribute.
Change the logical flow of statements Change the logical flow of statements by using control structures.by using control structures. Conditional (IF statement)Conditional (IF statement) Loops:Loops:
• Basic loopBasic loop• FOR loopFOR loop• WHILE loopWHILE loop• EXIT statementEXIT statement
Change the logical flow of statements Change the logical flow of statements by using control structures.by using control structures. Conditional (IF statement)Conditional (IF statement) Loops:Loops:
• Basic loopBasic loop• FOR loopFOR loop• WHILE loopWHILE loop• EXIT statementEXIT statement
SummarySummarySummarySummary