1 writing control structures part d. 2 pl/sql decision control structures sequential processing...
TRANSCRIPT
1
Writing Control Writing Control StructuresStructures
Part DPart D
2
PL/SQL Decision Control PL/SQL Decision Control StructuresStructures
Sequential processing Sequential processing Processes statements one after anotherProcesses statements one after another
Decision control structures Decision control structures Alter order in which statements executeAlter order in which statements execute Based on values of certain variablesBased on values of certain variables
3
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 You can change the logical flow of statements using flow of statements using conditional IF statements and conditional IF statements and loop control structures. loop control 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 You can change the logical flow of statements using flow of statements using conditional IF statements and conditional IF statements and loop control structures. loop control 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
4
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;
5
PL/SQL Comparison PL/SQL Comparison OperatorsOperators
6
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;. . .
7
IF-THEN-ELSE IF-THEN-ELSE Statement Execution Statement Execution
FlowFlow
IF-THEN-ELSE IF-THEN-ELSE Statement Execution Statement Execution
FlowFlowIF conditionIF condition
TRUETRUE
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)
8
IF-THEN-ELSE IF-THEN-ELSE StatementsStatements
IF-THEN-ELSE IF-THEN-ELSE StatementsStatements
Set a flag for orders where there Set a flag for orders where there are fewer than five days are fewer than five days between order date and ship between order date and ship date.date.
ExampleExample
Set a flag for orders where there Set a flag for orders where there are fewer than five days are fewer than five days between order date and ship between order date and ship date.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;...
9
IF-THEN-ELSIF IF-THEN-ELSIF Statement Execution Statement Execution
FlowFlow
IF-THEN-ELSIF IF-THEN-ELSIF Statement Execution Statement Execution
FlowFlowIF conditionIF condition
TRUETRUE
THEN actionsTHEN actionsTHEN actionsTHEN actions
FALSEFALSE
ELSIFELSIFconditioncondition
ELSIFELSIFconditioncondition
TRUETRUE
THEN actionsTHEN actionsTHEN actionsTHEN actions
FALSEFALSE
ELSEELSEactionsactionsELSEELSE
actionsactions
10
IF-THEN-ELSIF IF-THEN-ELSIF StatementsStatements
IF-THEN-ELSIF IF-THEN-ELSIF StatementsStatements
For a given value, calculate a For a given value, calculate a percentage of that value based percentage of that value based on a condition.on a condition.
ExampleExample
For a given value, calculate a For a given value, calculate a percentage of that value based percentage of that value based on a condition.on a 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;. . .
11
Building Logical Building Logical ConditionsConditions
Building Logical Building Logical ConditionsConditions
You can handle null values with the You can handle null values with the IS NULL operator.IS NULL operator.
Any arithmetic expression Any arithmetic expression containing a null value evaluates to containing a null value evaluates to NULL.NULL.
Concatenated expressions with null Concatenated expressions with null values treat null values as an values treat null values as an empty string.empty string.
NULL acts as FalseNULL acts as False The IS NULL condition evaluates to The IS NULL condition evaluates to
TRUE only if the variable it is TRUE only if the variable it is checking is NULL.checking is NULL.
You can handle null values with the You can handle null values with the IS NULL operator.IS NULL operator.
Any arithmetic expression Any arithmetic expression containing a null value evaluates to containing a null value evaluates to NULL.NULL.
Concatenated expressions with null Concatenated expressions with null values treat null values as an values treat null values as an empty string.empty string.
NULL acts as FalseNULL acts as False The IS NULL condition evaluates to The IS NULL condition evaluates to
TRUE only if the variable it is TRUE only if the variable it is checking is NULL.checking is NULL.
12
Logic TablesLogic TablesLogic TablesLogic Tables
Build a simple Boolean condition Build a simple Boolean condition with a comparison operator.with a comparison operator.
Build a simple Boolean condition Build a simple Boolean condition with a comparison operator.with 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
13
Boolean ConditionsBoolean ConditionsBoolean ConditionsBoolean Conditions
What is the value of V_FLAG in What is the value of V_FLAG in each case?each case?
What is the value of V_FLAG in What is the value of V_FLAG in each case?each case?
V_REORDER_FLAG V_AVAILABLE_FLAG V_FLAG
TRUE TRUE
TRUE FALSE
NULL TRUE
NULL FALSE
v_flag := v_reorder_flag AND v_available_flag; v_flag := v_reorder_flag AND v_available_flag;
TRUETRUE
FALSEFALSE
NULLNULL
FALSEFALSE
14
Evaluating AND and OR Evaluating AND and OR in an Expressionin an Expression
15
LoopsLoops
Systematically executes program Systematically executes program statementsstatements
Periodically evaluates exit condition to Periodically evaluates exit condition to determine if loop should repeat or exitdetermine if loop should repeat or exit
Pretest loopPretest loop Evaluates exit condition before any program Evaluates exit condition before any program
commands executecommands execute Posttest loop Posttest loop
Executes program commands before loop Executes program commands before loop evaluates exit condition for first timeevaluates exit condition for first time
16
Iterative Control: LOOP Iterative Control: LOOP StatementsStatements
Iterative Control: LOOP Iterative Control: LOOP StatementsStatements
Loops repeat a statement or Loops repeat a statement or sequence of statements multiple sequence of statements multiple times.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 Loops repeat a statement or sequence of statements multiple sequence of statements multiple times.times.
There are three loop types:There are three loop types: Basic loopBasic loop FOR loopFOR loop WHILE loopWHILE loop
17
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
•A basic loop can contain multiple EXIT statements.•A basic loop can contain multiple EXIT statements.
18
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
19
FOR LoopFOR LoopFOR LoopFOR Loop SyntaxSyntax
Use a FOR loop to shortcut the test Use a FOR loop to shortcut the test for the number of iterations.for the number of iterations.
Do not declare the counter; it is Do not declare the counter; it is declared implicitly.declared implicitly.
The lower bound and upper bound The lower bound and upper bound of the loop range can be literals, of the loop range can be literals, variables, or expressions, variables, or expressions, but must but must evaluate to integersevaluate to integers
SyntaxSyntax
Use a FOR loop to shortcut the test Use a FOR loop to shortcut the test for the number of iterations.for the number of iterations.
Do not declare the counter; it is Do not declare the counter; it is declared implicitly.declared implicitly.
The lower bound and upper bound The lower bound and upper bound of the loop range can be literals, of the loop range can be literals, variables, or expressions, variables, or expressions, but must but must evaluate to integersevaluate to integers
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;
20
FOR LoopFOR LoopFOR LoopFOR Loop GuidelinesGuidelines
Reference the counter within the Reference the counter within the loop only; it is undefined outside the loop only; it is undefined outside the loop.loop.
The lower and upper bounds of the The lower and upper bounds of the loop could be values, variables, or loop could be values, variables, or expressionsexpressions
Do Do notnot reference the counter as the reference the counter as the target of an assignment. An error target of an assignment. An error message rises if you do so.message rises if you do so.
GuidelinesGuidelines Reference the counter within the Reference the counter within the
loop only; it is undefined outside the loop only; it is undefined outside the loop.loop.
The lower and upper bounds of the The lower and upper bounds of the loop could be values, variables, or loop could be values, variables, or expressionsexpressions
Do Do notnot reference the counter as the reference the counter as the target of an assignment. An error target of an assignment. An error message rises if you do so.message rises if you do so.
21
FOR LoopFOR LoopFOR LoopFOR Loop Insert the first 10 new line items Insert the first 10 new line items
for order number 601.for order number 601. ExampleExample
Insert the first 10 new line items Insert the first 10 new line items for order number 601.for 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;
22
WHILE LoopWHILE LoopWHILE LoopWHILE Loop
SyntaxSyntax
Use the WHILE loop to Use the WHILE loop to repeat statements while a repeat statements while a condition is TRUE.condition is TRUE.
SyntaxSyntax
Use the WHILE loop to Use the WHILE loop to repeat statements while a repeat statements while a condition is TRUE.condition is TRUE.
WHILE condition LOOP statement1; statement2; . . .END LOOP;
WHILE condition LOOP statement1; statement2; . . .END LOOP;
Condition isCondition isevaluated at the evaluated at the beginning ofbeginning ofeach iteration.each iteration.
23
WHILE LoopWHILE LoopWHILE LoopWHILE Loop ExampleExample ExampleExample
SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: 'SQL>ACCEPT num_depts PROMPT 'Enter number of depts: ' SQL>DECLAREv_count NUMBER(2) := 1;BEGIN WHILE v_count <= &num_depts LOOP INSERT INTO dept(deptno,dname) VALUES (v_count, &v_dept_name); v_count := v_count + 1; END LOOP; COMMIT;END;/
SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: 'SQL>ACCEPT num_depts PROMPT 'Enter number of depts: ' SQL>DECLAREv_count NUMBER(2) := 1;BEGIN WHILE v_count <= &num_depts LOOP INSERT INTO dept(deptno,dname) VALUES (v_count, &v_dept_name); v_count := v_count + 1; END LOOP; COMMIT;END;/
24
Working with Working with Composite Composite DatatypesDatatypes
Working with Working with Composite Composite DatatypesDatatypes
25
The %ROWTYPE The %ROWTYPE AttributeAttribute
The %ROWTYPE The %ROWTYPE AttributeAttribute
Declare a variable according to a Declare a variable according to a collection of columns in a database collection of columns in a database table or view.table or view.
Prefix %ROWTYPE with the Prefix %ROWTYPE with the database table.database table.
Fields in the record take their Fields in the record take their names and datatypes from the names and datatypes from the columns of the table or view.columns of the table or view.
Declare a variable according to a Declare a variable according to a collection of columns in a database collection of columns in a database table or view.table or view.
Prefix %ROWTYPE with the Prefix %ROWTYPE with the database table.database table.
Fields in the record take their Fields in the record take their names and datatypes from the names and datatypes from the columns of the table or view.columns of the table or view.
26
The %ROWTYPE The %ROWTYPE AttributeAttribute
The %ROWTYPE The %ROWTYPE AttributeAttribute
ExamplesExamples Declare a variable to store the Declare a variable to store the
same information about a same information about a department as it is stored in the department as it is stored in the DEPT table. DEPT table.
Declare a variable to store the Declare a variable to store the same information about an same information about an employee as it is stored in the employee as it is stored in the EMP table.EMP table.
ExamplesExamples Declare a variable to store the Declare a variable to store the
same information about a same information about a department as it is stored in the department as it is stored in the DEPT table. DEPT table.
Declare a variable to store the Declare a variable to store the same information about an same information about an employee as it is stored in the employee as it is stored in the EMP table.EMP table.
dept_record dept%ROWTYPE; dept_record dept%ROWTYPE;
emp_record emp%ROWTYPE; emp_record emp%ROWTYPE;
27
%ROWTYPE Example%ROWTYPE Example
SQL> SET SERVEROUTPUT ON;SQL> SET SERVEROUTPUT ON;SQL> DECLARESQL> DECLARE d dept%ROWTYPE;d dept%ROWTYPE; BEGINBEGIN SELECT deptno,dname,loc INTO d SELECT deptno,dname,loc INTO d
FROM dept WHERE deptno=10;FROM dept WHERE deptno=10; DBMS_OUTPUT.PUT_LINE(d.dname);DBMS_OUTPUT.PUT_LINE(d.dname); END;END; //ACCOUNTINGACCOUNTING