PL/SQL Loops: FOR Loop and Control Statements
46 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What happens if you attempt to modify the counter_variable within a numeric FOR loop in PL/SQL?

  • The loop will terminate immediately, raising an exception.
  • The code will not compile due to a syntax error.
  • The modification will be ignored, and the loop will continue with its original increment. (correct)
  • The `counter_variable` will be updated, affecting subsequent iterations.

Given a requirement to iterate through a sequence with a specific step (e.g., 2, 5, 8, 11, 14), what is the most appropriate PL/SQL approach using a numeric FOR loop?

  • Utilize the `CONTINUE` statement to skip iterations that don't match the desired sequence.
  • Modify the `counter_variable` inside the loop using `i := i + step;`.
  • Perform a calculation within the loop using the `counter_variable` to achieve the desired sequence. (correct)
  • Use a `WHILE` loop instead of a `FOR` loop to allow manual incrementing.

If a numeric FOR loop is defined with a start_value greater than the end_value (e.g., FOR i IN 10..1), what will be the result?

  • The loop will not execute at all. (correct)
  • The loop will execute once, with the `counter_variable` set to `start_value`.
  • An error will be raised, halting the program execution.
  • The loop will execute in reverse order, decrementing from `start_value` to `end_value`.

In a numeric FOR loop in PL/SQL, what data types are acceptable for the start_value and end_value?

<p>Numeric values, numeric variables, and numeric expressions are allowed. (A)</p> Signup and view all the answers

What will be the output of the following PL/SQL code snippet?

declare
  total integer := 0;
begin
  for i in reverse 1..3 loop
    total := total + i;
  end loop;
  dbms_output.put_line(total);
end;
/

<p>6 (A)</p> Signup and view all the answers

What is the primary purpose of the exit when statement within a PL/SQL loop?

<p>To terminate the loop prematurely based on a specified condition. (C)</p> Signup and view all the answers

Within a numeric FOR loop in PL/SQL, what happens if the counter variable is not explicitly declared before the loop?

<p>The counter variable is implicitly declared and is valid only within the loop. (D)</p> Signup and view all the answers

What is the result of the condition x IS NULL in PL/SQL?

<p>It checks if the variable x currently holds a NULL value. (C)</p> Signup and view all the answers

Which operator is used in PL/SQL to check if a variable does not have a NULL value?

<p>IS NOT NULL (B)</p> Signup and view all the answers

What happens if you attempt to modify the counter variable's value inside a numeric FOR loop in PL/SQL?

<p>PL/SQL raises an error, and the compilation fails. (A)</p> Signup and view all the answers

What will be the output of the following PL/SQL code block?

declare
  total integer := 0;
begin
  for i in 1..5 loop
    total := total + i;
  end loop;
  dbms_output.put_line(total);
End;

<p>15 (A)</p> Signup and view all the answers

What is the difference between a basic LOOP and a numeric FOR loop in PL/SQL regarding the loop counter?

<p>A <code>FOR</code> loop automatically increments or decrements the loop counter; a basic LOOP requires manual update. (D)</p> Signup and view all the answers

In PL/SQL, what is the significance of the reverse keyword in a numeric FOR loop?

<p>It causes the loop to iterate in descending order from the end value to the start value. (A)</p> Signup and view all the answers

Which statement accurately describes the difference between named and anonymous PL/SQL blocks?

<p>Named blocks can be called by other programs and accept parameters, while anonymous blocks cannot. (D)</p> Signup and view all the answers

What is the correct structure of an anonymous PL/SQL block?

<p><code>declare variables begin statements exception handle exceptions end</code> (A)</p> Signup and view all the answers

What is the purpose of the SET SERVEROUTPUT ON; command in SQL Developer when working with PL/SQL?

<p>It enables the display of output from PL/SQL programs. (A)</p> Signup and view all the answers

Which DBMS_OUTPUT procedure would you use to display a variable's value on the screen, followed by a new line?

<p><code>DBMS_OUTPUT.PUT_LINE;</code> (D)</p> Signup and view all the answers

Given the following PL/SQL snippet, what will be the output?

declare
  message varchar2(20) := 'Hello';
begin
  dbms_output.put(message);
  dbms_output.put(' World');
end;
/

<p><code>Hello World</code> (D)</p> Signup and view all the answers

Which operator is used for assigning a value to a variable in PL/SQL?

<p>:= (B)</p> Signup and view all the answers

What does table-name.column-name%TYPE do in a PL/SQL declaration?

<p>It declares a variable with the same data type as the specified column. (D)</p> Signup and view all the answers

What is the scope of a variable declared inside a PL/SQL block?

<p>It is valid within the <code>BEGIN...END</code> block where it is declared. (C)</p> Signup and view all the answers

How do you create a single-line comment in PL/SQL?

<p><code>-- comment</code> (B)</p> Signup and view all the answers

Which of the following PL/SQL blocks will execute without any errors?

<pre><code class="language-sql">declare x number; begin x := 10; dbms_output.put_line('The value of x is: ' || x); end; ``` (D) </code></pre> Signup and view all the answers

When should an explicit cursor be used instead of an implicit cursor?

<p>When the query may return multiple records or no records. (A)</p> Signup and view all the answers

In PL/SQL, what happens if a query within an implicit cursor returns more than one row and no exception handling is in place?

<p>A <code>too_many_rows</code> exception is raised. (C)</p> Signup and view all the answers

When defining a function in SQL, what clause is used to specify the data type of the value that the function will output?

<p>RETURNS (A)</p> Signup and view all the answers

What is the primary difference between a SQL function and a SQL procedure, based on the content?

<p>Functions must return a value, while procedures do not necessarily return any value. (B)</p> Signup and view all the answers

Which action is not part of the correct sequence of steps when using an explicit cursor in PL/SQL?

<p>Fetching data outside a loop to improve performance. (D)</p> Signup and view all the answers

What is the purpose of the %notfound attribute when working with explicit cursors in PL/SQL?

<p>It indicates that the last fetch operation returned no rows. (B)</p> Signup and view all the answers

Which of the following methods is correct for invoking a SQL procedure?

<p>Using the <code>CALL</code> statement from an anonymous block. (D)</p> Signup and view all the answers

Given the function definition CREATE OR REPLACE FUNCTION calculate_bonus (salary NUMBER) RETURN NUMBER, which of the following describes the input parameter?

<p>The input parameter is named <code>salary</code> and its data type is <code>NUMBER</code>. (C)</p> Signup and view all the answers

Why is it important to close an explicit cursor after using it in PL/SQL?

<p>To release the resources held by the cursor. (A)</p> Signup and view all the answers

What is the correct order of operations inside the loop when fetching data using an explicit cursor?

<p>Fetch, exit test, process results. (B)</p> Signup and view all the answers

What clause is used in a SQL function or procedure to handle errors or exceptions that may occur during its execution?

<p>EXCEPTION (C)</p> Signup and view all the answers

In the example provided for creating the get_salary procedure, what is the purpose of the dbms_output.put_line function?

<p>To print the salary to the console or output. (D)</p> Signup and view all the answers

Which of the following is a common error to avoid when working with explicit cursors in PL/SQL?

<p>Forgetting to check the exit condition within the loop. (D)</p> Signup and view all the answers

When defining a procedure, what is the significance of the IS or AS keyword following the parameter list?

<p>It marks the beginning of the declaration section where local variables can be defined. (B)</p> Signup and view all the answers

What is the primary benefit of using functions and procedures in a database environment?

<p>They allow business logic to be stored and executed within the database. (D)</p> Signup and view all the answers

Consider a scenario where you need to reuse a complex SQL query multiple times within different parts of your application. Based on the provided content, which approach would be most efficient?

<p>Creating a SQL function that encapsulates the query logic. (C)</p> Signup and view all the answers

Inside the declaration section when using explicit cursors, what is the purpose of using %TYPE?

<p>It ensures that a variable has the same datatype as a column in the table. (A)</p> Signup and view all the answers

Which of the following is a key advantage of using explicit exception handling in PL/SQL?

<p>It allows the program to continue execution even when errors occur. (C)</p> Signup and view all the answers

What type of trigger is audit_instructor?

<p>A statement-level trigger that executes once after the triggering event. (A)</p> Signup and view all the answers

Which of the following SQL statements will cause the change_inst_dept trigger to execute?

<p><code>UPDATE instructor SET dept_name = 'Finance' WHERE id = 10101;</code> (C)</p> Signup and view all the answers

What is the primary purpose of the :new and :old qualifiers in the change_inst_dept trigger?

<p>To access the new and old values of the row being updated, respectively. (D)</p> Signup and view all the answers

Which of the following components is mandatory in the syntax for creating a row-level trigger?

<p>Specifying <code>BEFORE</code> or <code>AFTER</code>. (A)</p> Signup and view all the answers

If the condition new.salary < old.salary is added to the WHEN clause of a row-level trigger on the instructor table, under what circumstances would the trigger body execute?

<p>Whenever an instructor's salary is decreased. (B)</p> Signup and view all the answers

Flashcards

Anonymous PL/SQL Block

A PL/SQL program with no name that is not stored in the database after execution.

Basic PL/SQL Block Structure

Variables are declared, statements are executed, and exceptions are handled.

Named PL/SQL Blocks

PL/SQL programs stored as compiled objects in the database, can take parameters, and be called by other programs.

PL/SQL Comments

Delimit a block comment or start a single-line comment.

Signup and view all the flashcards

SET SERVEROUTPUT ON;

Enables the display of output from PL/SQL programs in SQL Developer.

Signup and view all the flashcards

DBMS_OUTPUT Package

A PL/SQL package used to display output. Includes PUT (no newline) and PUT_LINE (with newline).

Signup and view all the flashcards

Variables

Allocate memory to store values.

Signup and view all the flashcards

Variable Declaration Syntax

Specify the variable's name and data type.

Signup and view all the flashcards

Scope of Variable

The region where a variable is valid and can be accessed.

Signup and view all the flashcards

Assignment Statements

Assigns a value to a variable, using := operator.

Signup and view all the flashcards

Modifying Loop Counter

The counter variable in a numeric FOR loop cannot be directly modified inside the loop's body.

Signup and view all the flashcards

ELSE Clause

Part of an IF-THEN-ELSE construct that executes if the initial condition is false.

Signup and view all the flashcards

Comparison Operators

Symbols used to compare values in PL/SQL, like =, !=, >, <, >=, and <=.

Signup and view all the flashcards

Loop Counter Increment

In PL/SQL, the counter variable in a numeric FOR loop increments (or decrements with REVERSE) by 1 with each iteration. There is no direct syntax to change this step.

Signup and view all the flashcards

start_value > end_value

If start_value is greater than end_value in a forward FOR loop, the loop body will not execute.

Signup and view all the flashcards

IS NULL / IS NOT NULL

Used to check if a variable has no value assigned.

Signup and view all the flashcards

Numeric FOR Loop skipped

In PL/SQL, a FOR loop iterates from start_value to end_value (inclusive), but if start_value exceeds end_value, the code inside the loop will be skipped

Signup and view all the flashcards

Loop

A control structure that repeats a block of code until an exit condition is met.

Signup and view all the flashcards

Numeric FOR Loop

A PL/SQL loop construct that repeats a set number of times based on a counter variable.

Signup and view all the flashcards

FOR LOOP Value Types

The start_value and end_value of a FOR LOOP can be numeric values, variables, or expressions.

Signup and view all the flashcards

REVERSE Keyword

Keyword used in a FOR loop to specify counting down from the end value to the start value.

Signup and view all the flashcards

EXIT WHEN Statement

Statement used to prematurely exit a loop, even if the loop's main condition hasn't been met.

Signup and view all the flashcards

FOR Loop Counter Limitation

The counter variable is only valid inside a loop and cannot be modified within the loop's body.

Signup and view all the flashcards

SQL Procedure

A named (stored) module that performs one or more actions; it does not need to return any values.

Signup and view all the flashcards

SQL Function Definition

A function defined using SQL's procedural components or external languages like Java or C++.

Signup and view all the flashcards

CREATE FUNCTION syntax

Used to create a function in SQL. Includes the function name, parameters, return type, and function body.

Signup and view all the flashcards

Invoking SQL Functions

Invoking a previously created SQL function.

Signup and view all the flashcards

Invoking from Anonymous Program

A block of code that calls a SQL function and prints the returned salary.

Signup and view all the flashcards

CREATE PROCEDURE syntax

Used to create a stored procedure in SQL. Includes procedure name, parameters, and procedure body.

Signup and view all the flashcards

Invoking SQL Procedures

Invoking or calling a SQL procedure to execute its actions.

Signup and view all the flashcards

CALL statement

A statement used to call stored procedures from SQL procedures, anonymous blocks, or embedded SQL.

Signup and view all the flashcards

Database Trigger

A database object that automatically executes in response to certain events on a table (e.g., insert, update, delete).

Signup and view all the flashcards

Statement-Level Trigger

A trigger that executes once for the entire triggering statement (e.g., after an update on a table).

Signup and view all the flashcards

Row-Level Trigger

A trigger that executes for each row affected by the triggering statement.

Signup and view all the flashcards

Trigger Timing

Keywords specifying when the trigger executes relative to the triggering event (BEFORE or AFTER).

Signup and view all the flashcards

:OLD and :NEW

Used in row-level triggers to reference the old and new values of a column that is being updated.

Signup and view all the flashcards

Exception

A block of code that handles errors during program execution, preventing abrupt program termination.

Signup and view all the flashcards

EXCEPTION Syntax

Exception handling syntax allows for specific error handling (e.g., NO_DATA_FOUND) or a general handler (OTHERS).

Signup and view all the flashcards

Implicit Cursor Exceptions

NO_DATA_FOUND occurs when a SELECT statement returns no rows. TOO_MANY_ROWS happens when a SELECT statement returns more rows than expected.

Signup and view all the flashcards

Implicit Cursor Usage

Use implicit cursors only for queries that return zero or one row (primary key lookups) or aggregations without a GROUP BY clause.

Signup and view all the flashcards

Explicit Cursors

Cursors that you explicitly declare, open, fetch from, and close. Required when a query might return multiple records.

Signup and view all the flashcards

Explicit Cursor Steps

Declare -> Open -> Loop (Fetch -> Exit Check -> Process) -> Close.

Signup and view all the flashcards

Cursor Definition

An SQL statement that defines the result set the cursor will iterate through.

Signup and view all the flashcards

Cursor SQL Test

Always test your SQL statement independently before placing inside cursor definition in order to ensure it works.

Signup and view all the flashcards

Common Cursor Errors

Missing exit condition, forgetting to open/close/fetch, incorrect loop order.

Signup and view all the flashcards

Stored Procedures

Functions and procedures allow complex operations and business rules to be run from SQL (Stored Procedures).

Signup and view all the flashcards

Study Notes

  • Chapter 5 is about Advanced SQL, including PL/SQL structure, functions, procedures, and triggers.

Is SQL Powerful Enough?

  • It's important to determine when raw SQL falls short, such as needing multiple SQL statements for a single task.
  • SQL lacks native variables, loops, and conditional logic (if-then-else).
  • Considerations should include how to enable reusability of SQL statements and handle errors during query execution.

Why PL/SQL?

  • Embedding SQL into procedural languages like Java using JDBC/ODBC requires the client program to compute intermediate credit scores which can be solved with PL/SQL.
  • Oracle Procedure Language/SQL extends SQL with procedural language features and can be stored or used by other users.
  • Benefits include reduced communication costs, increased portability and security, and a manageable learning curve.
  • Downsides involve DBMS choice, lack of a GUI, and memory usage considerations.

Structure of PL/SQL

  • PL/SQL code is structured in blocks that are the fundamental building units
  • A block can be named for functions or procedures or can be anonymous.

Anonymous PL/SQL program:

  • Lacks a name
  • Is not stored in the database
  • Code is lost after execution.
  • Can be saved as a local script file but requires manual saving and loading.
  • Cannot accept/pass parameter values.
  • Structures include optional declare and exception sections, and a mandatory begin...end; section.
  • The subprogram is unnamed and can be used only once

Named PL/SQL Programs

  • Named PL/SQL programs which include functions and procedures are stored as compiled database objects.
  • They accept parameters for input and can be called and executed by other programs/users.

PL/SQL Code

  • PL/SQL code can span multiple lines.
  • Each line must end with a semicolon.
  • PL/SQL text is not case-sensitive.

PL/SQL Comments:

  • Multiline comments use /* */ delimiters.
  • Single line comments use -- at the start of the line.

Displaying PL/SQL Output:

  • PL/SQL is generally used with other Oracle tools.
  • To enable output from PL/SQL programs in SQL Developer use, SET SERVEROUTPUT ON.
  • serveroutput must be enabled each login.
  • The DBMS_OUTPUT package is used for output.
    • DBMS_OUTPUT.PUT(item) outputs without an end-of-line.
    • DBMS_OUTPUT.PUT_LINE(item) outputs with an end-of-line.
    • Item can be VARCHAR2, NUMBER, or INTEGER.

Variables in PL/SQL

  • Variables store values within PL/SQL programs.
  • Steps include declaring the variable name and data type then using the variable, either assigning or using the values in queries.
  • Variables are declared using variable_name data_type; and assigned values with variable_name := value;

Variable Scope

  • Scope refers to the range in which a variable is considered valid, defined by the begin … end block.
  • Variables are valid within the begin … end block after it's declared.

Assignment Statements

  • Assign values to variables using the := operator.
  • Put the receiving variable on the left, and the value being assigned to the right such as: student_name := 'John Miller';

Referring to Column Data Types

  • Use the %type to assign a variable the same data type and length of a table column automatically.
  • The syntax used is table_name.column_name%type.

Row Type Variables

  • Use %rowtype to declare a variable that represents an entire row of a database table.
  • Access columns within the row with variable_name.column_name.
  • Often used with the insert command to store results of an SQL query.

Common Errors

  • Forgetting a % between table name and row type.
  • Using . instead of % between table name and column name.
  • Using dbms_output.put_line() directly with a row type variable.
  • Solution: Access individual columns or use other methods to display the row_type output

PL/SQL Control Structures

  • PL/SQL Control Structures includes conditional if and case statements.
  • PL/SQL Control Structures includes loop and exit statements.

PL/SQL Selection Structures

  • IF/END IF: IF condition THEN program statements END IF;
  • IF/ELSIF: includes IF condition1 THEN program statements; ELSIF condition2 THEN alternate program statements; ELSE alternate program statements; END IF;

PL/SQL Comparison Operators

  • Comparison operators includes =, <>, >=, <=, <, and >.
  • Logical operators include AND, OR, and NOT.
  • Use IF x is NULL THEN for checking NULL values, because IF x = NULL THEN is not supported
  • Avoid “IF x = NULL THEN “ and instead check “IF x is NULL THEN”

PL/SQL Loops

  • Loops allow you to repeat one or more program statements multiple times until an exit condition is reached.
  • They are useful when processing SQL query results.
  • Use the basic loop construct with an exit when clause to control termination.
    • Example: loop total := total + i; i := i + 1; exit when i > 10; end loop;

Numeric FOR Loop

  • The loop repeats end_value – start_value +1 times
  • FOR counter_variable IN [reverse ] start_value .. end_value LOOP program statements END LOOP;
  • When to jump out of loop, use exit when
  • Counter variable can not be modified inside the loop

Important Note

  • Be sure that start_value is lower than (or equal to) end_value

Using SQL Commands in PL/SQL Programs

  • Includes insert, update, delete, commit, and rollback.
  • To handle select statements, use cursors to hold.
  • Data Definition Statements (DDL) can be used through dynamic SQL.
    • DDL includes create, drop, alter, grant, and revoke statements.

Using Insert, Update, Delete

  • Can be used SQL commands like insert, update, and delete without referring to any variables.
  • Can use the insert into Emp values statement to write variables in PL/SQL.

Using a Row-type Variable

  • Use a row-type variable to write multiple values to the table at once, and the program only has to declare the table name.
  • Example: insert into Emp values x;

Implicit Cursors

  • Implicit Cursors require only one line of code to execute select statements, and retrieve results.
  • The output must fetch one and only one record, or there will be an error.
  • Variables must have been declared beforehand and have a data type that matches the query result.
  • The command used for results is "SELECT column1, column2...INTO variable1, variable2,..FROM tablename WHERE search_condition;"

Implicit Cursors, Common Errors

  • A common is no data found which means your selection returned no rows in the table
  • Variables do not match the row type or column type, and you need to test your statements first

Exception Handling

  • Use the exception block to handle errors like no data found or too many rows.
    • Example: when no data found then dbms_output.put_line('no rows found');

Exception Syntax

  • When exception name, the handle
  • List out all of the handled variables and their corresponding output message.
  • Use for implicit cursor exceptions no_data_found and too_many_rows, but they are case insensitive. Example: dbms_output.put_line('No rows found')
  • Handle exceptional conditions for null values.
  • Use if x is null then… or if x is not null then

Tips for Implicit Cursor

  • To perform the "where" condition on primary key with (zero or one rows).
  • To perform aggregations without grouping by (1 row)
  • Otherwise use explicit cursor (which is next).

Explicit Cursors

  • Explicit cursors are to be declared in program's DECLARE section.
  • It can be used if query returns multiple records or no records.
  • To implement it, you have to declare, open, fetch cursor result into PL/SQL, check exit condition, and close cursor.

Common Errors in Explicit Cursor

  • Ensure the SQL statement has been tested before defining the cursor with variables
  • Ensure the tables or names are the same, and ensure all conditions are checked

Correct Order

  1. Always fetch
  2. Exit test
  3. Process results

Functions and Procedures

  • Functions and procedures allow "business logic" for SQL statements to be stored in the database and executed.
  • These can be defined either by the procedural component of SQL or by an external programming language such as Java, C, or C++.

SQL functions:

  • The syntax to follow for functions is
  • Syntax includes CREATE [OR REPLACE] FUNCTION function_name (parameter datatype) RETURN datatype IS BEGIN function body RETURN return_value; END;

Declaring SQL Function:

  • When declaring SQL functions, name the id of the instructor, and return the salary for the instructor
  • Syntax includes: create or replace function return_salary (instructor_id number) return number is sal number; begin end;

Invoking SQL Functions

  • If you have a function "name", then invoke the function by using the name() within SQL to execute Syntax is name + return + select where id

Declaring SQL Procedures

  • Use the instructor table to create and declare SQL Procedures "get_salary" function, with the id of the instructor
  • Syntax includes create or replace procedure get_salary (instructor_id int) is instr_salary int; begin end;

Invoking SQL Procedures:

  • Procedures can be invoke on the selected salary and the id through SQL and embedding it on the SQL Example: begin get_salary(10101); end;

Triggers

  • Triggers represent statements executed automatically in the database.
  • It's important to specify the conditions to be executed with the trigger
  • To design a trigger, specify the actions.
  • Useful for enforcing complex constraints or business rules, auditing changes to a table but CANNOT have parameters.

Triggering Events

  • The triggering event can be insert, deleted or update
  • A trigger could be Before(trigger is executed before the action), or After (trigger is executed after the action)

Types of Triggers

  • Statement Level: triggers the statement with how many rows are modified
  • Row Level: trigger the statement with number of rows, and will NOT other rows

Statement Level

  • Triggers fire once, regardless of how many rows are modifie
  • Audits what triggers being implemented

Row Level

  • For most other situations.
  • Trigger fires once for each row that is affected.
  • Through two system variables: new and old.

Creating A Statement-Level Trigger:

  • Syntax requires a name and event with Before or After
  • Insert is a must for all -Example: CREATE OR REPLACE TRIGGER trigger_name {BEFORE AFTER} {INSERT or UPDATE or DELETE} ON table_name [DECLARE declare local variables here] BEGIN trigger body END;

Row-Level Trigger Example:

  • "Print when department names (dept_name) gets changed. Print: “name has changed dep from”+department + “to” + department
  • Must Declare the table on a trigger

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

2- Advanced SQL (PL-SQL).pptx

Description

Test your knowledge of PL/SQL loops, focusing on numeric FOR loops, REVERSE keyword, loop control using EXIT WHEN, and NULL value handling. Learn about iterating with specific steps and the implications of modifying loop counters.

More Like This

PL/SQL Triggers Quiz
5 questions
PL/SQL Quiz
5 questions

PL/SQL Quiz

ThriftyErudition avatar
ThriftyErudition
PL/SQL Composite Data Types Quiz
10 questions
PL/SQL Cursor FOR LOOP
16 questions

PL/SQL Cursor FOR LOOP

HeroicCornflower avatar
HeroicCornflower
Use Quizgecko on...
Browser
Browser