PL/SQL Blocks: Name, Birthday, and Age

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What function is used to calculate the difference between two dates in months?

  • `MONTHS_DIFF`
  • `DATE_DIFF`
  • `MONTHS_BETWEEN` (correct)
  • `MONTHS.DIFF`

In PL/SQL, you can directly embed SQL queries within the PL/SQL block to manipulate data.

True (A)

How can you display output in PL/SQL?

DBMS_OUTPUT.PUT_LINE

To declare a variable to store a string of varying length in PL/SQL, one would use the datatype ________.

<p><code>VARCHAR2</code></p> Signup and view all the answers

Match the PL/SQL components with their descriptions

<p>DECLARE = Used to define variables and constants BEGIN = Marks the start of the executable section of the PL/SQL block END = Marks the end of the PL/SQL block <code>DBMS_OUTPUT.PUT_LINE</code> = Used to output information</p> Signup and view all the answers

Which of the following is the correct way to declare a variable v_date of DATE type and initialize it to '2000-01-01' in PL/SQL?

<p><code>v_date DATE := TO_DATE('2000-01-01', 'YYYY-MM-DD');</code> (C)</p> Signup and view all the answers

In PL/SQL, comments started with -- extend until the end of the line only.

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

How do you define a multi-line comment in PL/SQL?

<p><code>/* ... */</code></p> Signup and view all the answers

To update the salary of an employee with employee_id = 122 in PL/SQL, you can use the _______ statement.

<p><code>UPDATE</code></p> Signup and view all the answers

Match the following terms with their descriptions:

<p><code>VARCHAR2</code> = Variable-length character string <code>NUMBER</code> = Numeric data type <code>DATE</code> = Date and time data type <code>BOOLEAN</code> = Logical data type that can be TRUE, FALSE, or NULL</p> Signup and view all the answers

Which of the following statements is true regarding NULL values in PL/SQL?

<p>You must use <code>IS NULL</code> or <code>IS NOT NULL</code> to check for <code>NULL</code> values. (C)</p> Signup and view all the answers

A reserved word can be used as a user-defined identifier by enclosing it in double quotes.

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

What is the purpose of the %TYPE attribute in PL/SQL?

<p>Declare a variable of the same datatype as a column in a table</p> Signup and view all the answers

The upper limit of PLS_INTEGER datatype is ________.

<p><code>2147483647</code></p> Signup and view all the answers

Match the following conditional statements with their correct function in PL/SQL:

<p><code>IF-THEN-ELSE</code> = Executes a segment of code based on a condition; executes alternate code if the condition is false. <code>CASE</code> = Selects a result from several alternatives based on the evaluation of multiple conditions.</p> Signup and view all the answers

Which statement is used to skip the current iteration of a loop in PL/SQL?

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

In PL/SQL, you can use named loops, which can be useful for clarity in nested loops.

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

What statement is used to exit a loop in PL/SQL?

<p><code>EXIT</code></p> Signup and view all the answers

To check if a number is even or odd in PL/SQL, you can use the ________ function.

<p><code>MOD</code></p> Signup and view all the answers

Match each loop type with its appropriate use case

<p><code>FOR</code> loop = Used when the number of iterations is known <code>WHILE</code> loop = Used when the number of iterations is not known in advance, and the loop continues as long as a condition is true <code>LOOP...EXIT</code> = Provides the most control, allowing for exit conditions anywhere within the loop</p> Signup and view all the answers

Which of the following is the correct syntax to use GOTO statement in a for loop?

<p><code>GOTO label;</code> (A)</p> Signup and view all the answers

When using the CONTINUE statement inside a loop, the statements after CONTINUE are skipped, and the loop restarts from its beginning.

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

In PL/SQL, what does SQL%ROWCOUNT return?

<p>Number of rows affected by the most recent SQL statement</p> Signup and view all the answers

Use _______ to manipulate data in PL/SQL

<p>SQL</p> Signup and view all the answers

Match the following cursor attributes with their descriptions:

<p><code>%FOUND</code> = Boolean attribute that is <code>TRUE</code> if the most recent fetch was successful; otherwise, it is <code>FALSE</code> <code>%NOTFOUND</code> = Boolean attribute that is <code>TRUE</code> if the most recent fetch returned no rows; otherwise, it is <code>FALSE</code> <code>%ROWCOUNT</code> = Returns the number of rows fetched from the cursor so far</p> Signup and view all the answers

What will be the state of %NOTFOUND if a cursor successfully fetches a row?

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

An explicit cursor must be declared and opened whereas implicit cursors are automatically managed by Oracle.

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

What keyword is used to retrieve values from a cursor into variables?

<p><code>FETCH</code></p> Signup and view all the answers

A cursor _____ allows you to perform DML operations one row at a time

<p><code>FOR UPDATE</code></p> Signup and view all the answers

Match the following types of cursors with their appropriate use cases:

<p>Explicit Cursors = Used for queries that return multiple rows, requiring manual control over the cursor's lifecycle. Implicit Cursors = Automatically created by Oracle for single-row SQL statements, simplifying code.</p> Signup and view all the answers

What is the purpose of using %ROWTYPE?

<p>To define a record structure that mirrors the columns of a table or a view. (A)</p> Signup and view all the answers

A cursor can be used in a FOR loop to process each row in the active set automatically.

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

Within a cursor FOR loop, how do you access the fields of the current row?

<p>Using the record name followed by the field name</p> Signup and view all the answers

You can specify that a cursor is _____ to prevent other users from modifying the rows while you are processing them.

<p><code>FOR UPDATE</code></p> Signup and view all the answers

Match cursor attributes with their usage

<p><code>OPEN</code> = Allocates memory for the cursor <code>FETCH</code> = Retrieves data from active set of the cursor <code>CLOSE</code> = Release memory for the cursor</p> Signup and view all the answers

What PL/SQL construct is used to encapsulate a series of operations into a named block that can be invoked multiple times?

<p>Procedure (D)</p> Signup and view all the answers

Procedures can return values to the calling environment, which is similar to functions.

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

In PL/SQL, how do you specify that a procedure parameter is an IN parameter?

<p>By specifying the parameter in the procedure declaration without an assignment operator</p> Signup and view all the answers

To replace a procedure, use CREATE OR _______ PROCEDURE statement.

<p><code>REPLACE</code></p> Signup and view all the answers

Which conditional logic structures are available in PL/SQL to handle complex situations?

<p>All of the above (D)</p> Signup and view all the answers

In PL/SQL, nested IF statements are generally preferred over using the ELSIF clause for better performance.

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

Flashcards

PL/SQL Print

A block of code in PL/SQL to print name, birthday and age

Age Calculator

PL/SQL to calculates your age in 10, 20 and 25 years

PL/SQL Day

A block of code to get the day you were born

PL/SQL Math

PL/SQL block where addition and subtraction are calculated

Signup and view all the flashcards

Employee Incentive

PL/SQL code to calculate the incentive of an employee with ID 110 using HR schema

Signup and view all the flashcards

Reserved Words

To shows that a reserved word can be used as a user-defined identifier.

Signup and view all the flashcards

PL/SQL Comments

Single-line comments begin with --, multi-line comments are enclosed in /* and */

Signup and view all the flashcards

Variable Declaration

v_name VARCHAR2(50), v_age NUMBER, v_salary NUMBER(10,2), v_hire_date DATE

Signup and view all the flashcards

Adjust Salary

PL/SQL block to adjust the salary of the employee with ID 122 via the HR schema employees table

Signup and view all the flashcards

Usage of NULL

NULL is never equal or unequal to other NULLs, use IS NULL to check nulls.

Signup and view all the flashcards

Character type

v_char_variable CHAR(10) := 'A'; , v_varchar_variable VARCHAR2(50) := 'Hello, PL/SQL!';

Signup and view all the flashcards

Insert Data

INSERT INTO employees (employee_id, first_name) VALUES (9999, v_employee_name);

Signup and view all the flashcards

Employee info

insert data into the departments table using a character type variable

Signup and view all the flashcards

Upper Limit

v_max PLS_INTEGER := 2147483647;

Signup and view all the flashcards

Conditional Assignment

IF v_num1 < v_num2 THEN num_small := v_num1;

Signup and view all the flashcards

Employee Salary

SELECT salary INTO v_salary FROM employees WHERE employee_id = p_employee_id;

Signup and view all the flashcards

Number Check

IF MOD(v_number, 2) = 0 THEN...END IF;

Signup and view all the flashcards

incentive Cal

IF p_target > 5000 THEN v_bonus := v_salary * 0.15;

Signup and view all the flashcards

Weekday check

IF v_day IN ('SAT', 'SUN') THEN (day of the week

Signup and view all the flashcards

Sales Condition

IF v_sales > 10000 THEN...

Signup and view all the flashcards

Vacancies check

IF v_employee_count < v_vacancies THEN

Signup and view all the flashcards

Grade description

CASE v_grade WHEN 'A' THEN

Signup and view all the flashcards

Number Sign

IF v_number > 0 THEN

Signup and view all the flashcards

Alphanumeric Character

IF v_char BETWEEN 'A' AND 'Z' OR ... THEN

Signup and view all the flashcards

Temp converstion

v_fahrenheit := (v_celsius * 9 / 5) + 32;

Signup and view all the flashcards

Date Check

v_day := TO_CHAR(v_date, 'Day');

Signup and view all the flashcards

Loop stop

EXIT WHEN v_counter = 5;

Signup and view all the flashcards

Nested Loops

FOR i IN 1..3 LOOP FOR j IN 1..3 LOOP

Signup and view all the flashcards

J Test

EXIT WHEN j = 2;

Signup and view all the flashcards

Skip Numbers

CONTINUE; -- Skip even numbers

Signup and view all the flashcards

Loop test

WHILE v_counter <= v_n LOOP

Signup and view all the flashcards

Varible check

DBMS_OUTPUT.PUT_LINE('Variable changed, but cursor remains unchanged.');

Signup and view all the flashcards

Join info

FROM employees e JOIN departments d ON e.department_id = d.department_id

Signup and view all the flashcards

salary check

SELECT first_name, last_name, salary - p_max_salary AS overpaid

Signup and view all the flashcards

Dates

WHERE TO_CHAR(hire_date, 'MM-YYYY') = TO_CHAR(SYSDATE, 'MM-YYYY')

Signup and view all the flashcards

Employee data

TYPE emp_record IS RECORD (

Signup and view all the flashcards

Data join

JOIN (SELECT department_id, department_name FROM departments)

Signup and view all the flashcards

Study Notes

  • PL/SQL (Procedural Language/SQL) is a programming language that extends SQL with procedural capabilities.
  • PL/SQL blocks are fundamental units of code, that can be named or anonymous.
  • Blocks consist of a DECLARE section, a BEGIN section, and an optional EXCEPTION section.

Printing Name, Birthday, and Age

  • A PL/SQL block can be created to print name, birthday, and age.
  • Variables are declared with VARCHAR2 for the name and DATE for the birthday.
  • The age is computed via TRUNC(MONTHS_BETWEEN(SYSDATE, Birthday) / 12) which determines the integer part of the age based on months since the birthday

Calculating Age in Future Years

  • A PL/SQL block determines future age in 10, 20, and 25 years.
  • It calculates the current age and subsequently adds 10, 20, and 25 years to that value.

Determining Day of the Week for a Given Birthday

  • A PL/SQL block outputs the day of the week someone was born.
  • It coverts the birthday date to a day string using TO_CHAR(v_birthday, 'Day').

Performing Addition and Subtraction

  • A PL/SQL block calculates the sum and difference of two numbers.
  • It declares two number variables, calculates their sum and difference and presents the results.

Calculating Employee Incentive

  • A PL/SQL block calculates an employee's incentive based on their salary.
  • It uses the employees table with the salary%TYPE attribute.
  • Incentives are calculated by multiplying the salary by 0.10.

Using Reserved Words as Identifiers

  • A PL/SQL block is created to show that reserved words can be used as user defined identifiers by surrounding them in double quotes.
  • Dubble quotes are valid “BEGIN” number := 10 .

Explaining Comments

  • Single-line comments start with --.
  • Multi-line comments are enclosed within /* and */.

Declaring Variables

  • Different datatypes are declared like VARCHAR2, NUMBER, and DATE.
  • Date are initialized with SYSDATE.

Adjusting Employee Salary

  • A PL/SQL block updates an employee's salary by 10%
  • The HR schema employees table is used.
  • The updated salary is displayed.

Usage of NULL Values

  • NULL is not equal to any value, including itself, during comparison.
  • IS NULL should be used to detect NULL values.

Declaring Character Type Variables

  • CHAR and VARCHAR2 variables are declared.
  • CHAR can be fixed-length, VARCHAR2 is variable-length.

Inserting Data with Character Type Variable

  • A PL/SQL block that inserts a new employee into the employees table using a VARCHAR2 variable for the first name.

Inserting Data into Departments Table

  • A PL/SQL code block that inserts a new department using VARCHAR2 for the department name.

Upper Limit of PLS_INTEGER

  • The maximum value for PLS_INTEGER is 2147483647.

Arranging Numbers

  • IF/ELSE statement arranges two numbers into num_small and num_large.

Procedure for Incentive Status

  • A procedure calculates and updates employee incentives.
  • SQL%ROWCOUNT checks for successful updates.

Even or Odd Check

  • The MOD function is used to check if a number is even or odd.
  • MOD(number, 2) = 0 indicates an even number.

Procedure for Incentive By Target

  • A procedure calculates bonus based on target.
  • It calculates a bonus based on whether an employee's target exceeds 5000.

Weekday Check Procedure

  • A procedure determines if a date is a weekend or a weekday
  • Built-in IN operator is used
  • Day converted using TO_CHAR

Incentive on Sales Limit

  • Incentive amounts are computed based on different sales thresholds, with varying percentages applied to sales figures.

Vacancies Check

  • A COUNT(*) statement determines the number of employees in department 50.

Display Grade Description

  • A CASE statement is used to output a grade description based on a grade.
  • It assigns descriptions such as 'Excellent', 'Good', 'Average', or 'Fail' based on the value of v_grade.

Vacancy Check in Department

  • Counts employee in department, then indicates if there are vacancies available in that department.

Display Grade with CASE

  • The CASE keyword allows you to SELECT results in the THEN part of the statement

Display Grade with CASE and Exception

  • Handled exceptions by calling RAISE_APPLICATION_ERROR.

Positive or Negative Check

  • An ELSIF statement can check if a number is negative.

Letter or Digit Check

  • BETWEEN can check for either a letter or digit.

Temperature Conversion

  • Used ROUND(temp,2) to give 2 DP

Specific Date Check

  • Built in TO_CHAR with parameter Day displays day of week that date falls on

Loop EXIT

  • EXIT WHEN command lets the loop end when the expression equates to true

Loop WHEN EXIT

  • A LOOP can be exited using the EXIT WHEN statement

Nested Loop

  • Inner and outer loops each repeat as indicated by 1..3 LOOP.

Update Salary with Mid-Range Check

  • Updates salaries based on conditions related to mid-salary range
  • v_mid_salary determined by (v_min_salary + v_max_salary) / 2

Nested Quit

  • Nested loops can check for specific values, can call Exit When command.

CONTINUE Statement

  • The CONTINUE statement skips the rest of the current loop iteration and proceeds to the next iteration.

CONTINUE WHEN Statement

  • The CONTINUE WHEN statement skips the rest of the statements in the loop iteration if the condition specified after WHEN.
  • A WHILE statement increments and displays values.

Addition N numbers

  • The loop iterates until the counter i reaches the specified limit v_n, printing output.

Local Variable

  • Assigning a local variable lets you override the global variable in the scope of the inner block.

Nested-FOR-Loop

  • The outer and inner loop have labels of outer_loop and inner_loop.
  • Used loop commands within for loops.

Prime Numbers

  • Check for prime numbers to a given number by using

GOTO PrimeNumber

  • A GOTO command can be used to go to a specific line, use <<label>> to set.

Insert from Table

  • Inserting from one table to another
  • Insert data into one table from another.

Insert Row

  • Checking it the salary is not null or salary is not valid.

Cursors

  • Cursors can select from a table with WHERE and other commands
  • Cursors can include %TYPE in the DECLARE statement
  • Shows total employee and displays result

CURVAL and NEXTVAL

  • A sequence increments and outputs value
  • employee_seq.NEXTVAL - selects the next in sequence
  • employee_seq.CURVAL – selects the current value
  • Displays two different output lines

SQL%ROWCOUNT

  • SQL%ROWCOUNT returns the number of rows affected by the most recent SQL statement.

Implicit Cursor Without Attribute

  • Updates or does not update rows, based on if it find an entry in the table.
  • Confirmed by Update executed successfully messages.

SQL%FOUND

  • The SQL%FOUND attribute used after DELETE determines if a delete executed.

SQL%NOTFOUND

  • The SQL%NOTFOUND used after UPDATE determines if a entry was updated.

Table-Based Record

  • Can select direct in to v_employee variable in employees%ROWTYPE
  • Outputs name of employee

Details of employee 149

  • Selecting direct from table gives you access to data
  • Easy to display output from table

Details with cursor

  • Create cursors to select from data
  • Display that data

Details cursor and retrieve display

  • Can create variable on the fly in SQL SELECT to display

Cursor Datatype

  • Creating a datatype is a good way to re-use code.

Implicit Cursor

  • Loops though table or cursor
  • Sets the record from the table, then select data
  • Outputs data

Explicit Cursor

  • Loops through table or cursor
  • Sets the record from the cursor, then select data
  • Outputs data

Salary with CURRENTOF

  • Select data and select from loop
  • Use CURRENTOF to update table as it loops through the selected data.

Fetch Single Record and Column

  • Fetch a single record and single column from a table is an easy and fast way to extract data and display it.

Fetch Single Column

  • Displays a column
  • Great way to display column

Multiple Records and Columns

  • Displays multiple values
  • Cursors are effective in pulling the data from the table.

Different Table Records

  • A join can select from different rows
  • A LOOP can display the data from a database join

Nested Cursors

  • Displays department ID
  • Displays employee connected to department ID

Cursor for Loops

  • Nestles functions and loops for use
  • Displays table information and labels them

Managers and the Department Name

  • Selects departments and the associated users
  • Displays the managers

Multiple Tables

  • Can select from multiple tables to insert information
  • Effective way to populate database.

Two Tables

  • Select data to join
  • Insert new data from joined table.

Create Cursor

  • Select first name, last name , salary
  • Fetch, process, output.

Fetch Statement

  • The code selects from the table
  • Creates cursor and then fetch though

First Three

  • Can select three from table
  • Using command num <= 3

Query cursor and variables

  • Assign value as var
  • Select that var, display output

List data

  • Creates view with managers last name table
  • Loops though output

Table select

  • Display table and values
  • Join statements use

Display Name Column

  • Data select, where condition, display output

Display records

  • Use sub query for department name.

Record in Table

  • Select employee id and employee name
  • Use “Record” parameter for types

Query in Cursor

  • Select information from sub query
  • Add on the value table on the on statement

Salary Increase

  • Calculate increase bases on date hire
  • Use math to calc

Studying That Suits You

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

Quiz Team

Related Documents

More Like This

Oracle PL/SQL Explicit Cursors Quiz
10 questions

Oracle PL/SQL Explicit Cursors Quiz

SimplestRainbowObsidian8987 avatar
SimplestRainbowObsidian8987
Tema 24. PL/SQL en Oracle
30 questions
PL/SQL: SQL, DML, DDL Statements and Cursors
29 questions
Use Quizgecko on...
Browser
Browser