SlideShare a Scribd company logo
1 of 5
Download to read offline
Downloaded From: http://www.cbseportal.com




                                 Chapter – 1
                                    PL/SQL
                                 (Informatics Practices)


PL/SQL = Procedural Language extensions to SQL
An Oracle-specific language combining features of:

      modern, block-structured programming language
      database interaction via SQL

Designed to overcome declarative SQL's inability to specify control aspects of DB
interaction.

Used to add procedural capabilities to Oracle tools.

PL/SQL is implemented via a PL/SQL engine (cf. JVM)

      which can be embedded in clients (e.g. Forms, SQL*Plus)
      which is also usually available in the Oracle server

Why PL/SQL?

Consider trying to implement the following in SQL (SQL*Plus):

If a user attempts to withdraw more funds than they have from their account, then
indicate "Insufficient Funds", otherwise update the account

A possible implementation:

      ACCEPT person PROMPT 'Name of account holder: '
      ACCEPT amount PROMPT 'How much to withdraw: '

      UPDATE Accounts
      SET balance = balance - &amount
      WHERE holder = '&person' AND balance > &amount;
      SELECT 'Insufficient Funds'
      FROM Accounts
      WHERE holder = '&person' AND balance < = &amount;

Two problems:

      doesn't express the "business logic" nicely
      performs both actions when (balance-amount < amount)

We could fix the second problem by reversing the order (SELECT then UPDATE).




                         Downloaded From: http://www.cbseportal.com
Downloaded From: http://www.cbseportal.com




But in SQL there's no way to avoid executing both the SELECT and the UPDATE

PL/SQL allows us to specify the control more naturally:
-- A sample PL/SQL procedure

PROCEDURE withdrawal(person IN varchar(20), amount IN REAL ) IS
  current REAL;
BEGIN
  SELECT balance INTO current
  FROM Accounts
  WHERE holder = person;
  IF (amount > current)
     dbms_output.put_line('Insufficient Funds');
  ELSE
     UPDATE Accounts
     SET balance = balance - amount
     WHERE holder = person AND balance > amount;
     COMMIT;
  END IF;
END;
And package it up into a useful function, which could be used as:
SQL> EXECUTE withdrawal('John Shepherd', 100.00);

PL/SQL Syntax

PL/SQL is block-structured, where a block consists of:

DECLARE
  declarations for
     constants, variables and local procedures
BEGIN
  procedural and SQL statements
EXCEPTION
  exception handlers
END;

Data Types

PL/SQL constants and variables can be defined using:

      standard SQL data types (CHAR, DATE, NUMBER, ...)
      built-in PL/SQL types (BOOLEAN, BINARY_INTEGER)
      PL/SQL structured types (RECORD, TABLE)

Users can also define new data types in terms of these.
There is also a CURSOR type for interacting with SQL.

Record Types

Corresponding to Modula RECORDs or Constructs, and also closely related to SQL table
row type.



                         Downloaded From: http://www.cbseportal.com
Downloaded From: http://www.cbseportal.com




New record types can be defined via:
  TYPE TypeName IS RECORD
      (Field1 Type1, Field2 Type2, ...);
Example:
  TYPE Student IS RECORD (
      id# NUMBER(6),
      name VARCHAR(20),
      course NUMBER(4)
  );
Record components are accessed via Var.Field notation.
  fred Student;
  ...
  fred.id# := 123456;
  fred.name := 'Fred';
  fred.course := 3978;
Record types can be nested.
  TYPE Day IS RECORD
      (day NUMBER(2), month NUMBER(2), year NUMBER(4));

   TYPE Person IS RECORD
     (name VARCHAR(20), phone VARCHAR(10), birthday Day);

Constants and Variables

Variables and constants are declared by specifying:
  Name [ CONSTANT ] Type [ := Expr ] ;

Examples:
  amount INTEGER;
  part_number NUMBER(4);
  in_stock BOOLEAN;
  owner_name VARCHAR(20);
  max_credit CONSTANT REAL := 5000.00;
  my_credit REAL := 2000.00;

Variables can also be defined in terms of:

      the type of an existing variable or table column
      the type of an existing table row (implict RECORD type)

Examples:

   employee Employees%ROWTYPE;
   name Employees.name%TYPE;

Assigning Values to Variables

A standard assignment operator is available:
  tax := price * tax_rate;
  amount := TO_NUMBER(SUBSTR('750 dollars',1,3));




                         Downloaded From: http://www.cbseportal.com
Downloaded From: http://www.cbseportal.com




Values can also be assigned via SELECT...INTO:
   SELECT price +10 INTO cost
  FROM StockList
  WHERE item = 'Cricket Bat';
  total := total + cost;

SELECT...INTO can assign a whole row at once:
    DECLARE
      emp Employees%ROWTYPE;
      my_name VARCHAR(20);
      pay NUMBER(8,2);
    BEGIN
      SELECT * INTO emp
      FROM Employees
      WHERE id# = 966543;
      my_name := emp.name;
...
      SELECT name,salary INTO my_name,pay
      FROM Employees
      WHERE id# = 966543;
    END;

Control Structures

PL/SQL has conventional set of control structures:

      for sequence (note:- ; is a terminator)
      IF for selection
      FOR, WHILE, LOOP for repetition

Along with exceptions to interrupt normal control flow.
And a NULL; statement to do nothing.

Selection

Selection is expressed via:

   1. IF Cond1 THEN Statements1;
   2. ELSIF Cond2 THEN Statements2;
   3. ELSIF Cond3 THEN Statements3;

Example:

 If A > B Then                                  If A > B Then
    Dbms_output.put_line (‘A is big’);             Dbms_output.put_line (‘A is big’);
 End if;                                        ELSIF
                                                   Dbms_output.put_line (‘B is big’);
                                                End if;




                          Downloaded From: http://www.cbseportal.com
Downloaded From: http://www.cbseportal.com




If A > B Then
   Dbms_output.put_line (‘A is big’);
ELSE
   Dbms_output.put_line (‘B is big’);
End if;




                        Downloaded From: http://www.cbseportal.com

More Related Content

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Featured

Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 

Class Xii E Book Informatics Practices Chapter 1 Pl Sql

  • 1. Downloaded From: http://www.cbseportal.com Chapter – 1 PL/SQL (Informatics Practices) PL/SQL = Procedural Language extensions to SQL An Oracle-specific language combining features of: modern, block-structured programming language database interaction via SQL Designed to overcome declarative SQL's inability to specify control aspects of DB interaction. Used to add procedural capabilities to Oracle tools. PL/SQL is implemented via a PL/SQL engine (cf. JVM) which can be embedded in clients (e.g. Forms, SQL*Plus) which is also usually available in the Oracle server Why PL/SQL? Consider trying to implement the following in SQL (SQL*Plus): If a user attempts to withdraw more funds than they have from their account, then indicate "Insufficient Funds", otherwise update the account A possible implementation: ACCEPT person PROMPT 'Name of account holder: ' ACCEPT amount PROMPT 'How much to withdraw: ' UPDATE Accounts SET balance = balance - &amount WHERE holder = '&person' AND balance > &amount; SELECT 'Insufficient Funds' FROM Accounts WHERE holder = '&person' AND balance < = &amount; Two problems: doesn't express the "business logic" nicely performs both actions when (balance-amount < amount) We could fix the second problem by reversing the order (SELECT then UPDATE). Downloaded From: http://www.cbseportal.com
  • 2. Downloaded From: http://www.cbseportal.com But in SQL there's no way to avoid executing both the SELECT and the UPDATE PL/SQL allows us to specify the control more naturally: -- A sample PL/SQL procedure PROCEDURE withdrawal(person IN varchar(20), amount IN REAL ) IS current REAL; BEGIN SELECT balance INTO current FROM Accounts WHERE holder = person; IF (amount > current) dbms_output.put_line('Insufficient Funds'); ELSE UPDATE Accounts SET balance = balance - amount WHERE holder = person AND balance > amount; COMMIT; END IF; END; And package it up into a useful function, which could be used as: SQL> EXECUTE withdrawal('John Shepherd', 100.00); PL/SQL Syntax PL/SQL is block-structured, where a block consists of: DECLARE declarations for constants, variables and local procedures BEGIN procedural and SQL statements EXCEPTION exception handlers END; Data Types PL/SQL constants and variables can be defined using: standard SQL data types (CHAR, DATE, NUMBER, ...) built-in PL/SQL types (BOOLEAN, BINARY_INTEGER) PL/SQL structured types (RECORD, TABLE) Users can also define new data types in terms of these. There is also a CURSOR type for interacting with SQL. Record Types Corresponding to Modula RECORDs or Constructs, and also closely related to SQL table row type. Downloaded From: http://www.cbseportal.com
  • 3. Downloaded From: http://www.cbseportal.com New record types can be defined via: TYPE TypeName IS RECORD (Field1 Type1, Field2 Type2, ...); Example: TYPE Student IS RECORD ( id# NUMBER(6), name VARCHAR(20), course NUMBER(4) ); Record components are accessed via Var.Field notation. fred Student; ... fred.id# := 123456; fred.name := 'Fred'; fred.course := 3978; Record types can be nested. TYPE Day IS RECORD (day NUMBER(2), month NUMBER(2), year NUMBER(4)); TYPE Person IS RECORD (name VARCHAR(20), phone VARCHAR(10), birthday Day); Constants and Variables Variables and constants are declared by specifying: Name [ CONSTANT ] Type [ := Expr ] ; Examples: amount INTEGER; part_number NUMBER(4); in_stock BOOLEAN; owner_name VARCHAR(20); max_credit CONSTANT REAL := 5000.00; my_credit REAL := 2000.00; Variables can also be defined in terms of: the type of an existing variable or table column the type of an existing table row (implict RECORD type) Examples: employee Employees%ROWTYPE; name Employees.name%TYPE; Assigning Values to Variables A standard assignment operator is available: tax := price * tax_rate; amount := TO_NUMBER(SUBSTR('750 dollars',1,3)); Downloaded From: http://www.cbseportal.com
  • 4. Downloaded From: http://www.cbseportal.com Values can also be assigned via SELECT...INTO: SELECT price +10 INTO cost FROM StockList WHERE item = 'Cricket Bat'; total := total + cost; SELECT...INTO can assign a whole row at once: DECLARE emp Employees%ROWTYPE; my_name VARCHAR(20); pay NUMBER(8,2); BEGIN SELECT * INTO emp FROM Employees WHERE id# = 966543; my_name := emp.name; ... SELECT name,salary INTO my_name,pay FROM Employees WHERE id# = 966543; END; Control Structures PL/SQL has conventional set of control structures: for sequence (note:- ; is a terminator) IF for selection FOR, WHILE, LOOP for repetition Along with exceptions to interrupt normal control flow. And a NULL; statement to do nothing. Selection Selection is expressed via: 1. IF Cond1 THEN Statements1; 2. ELSIF Cond2 THEN Statements2; 3. ELSIF Cond3 THEN Statements3; Example: If A > B Then If A > B Then Dbms_output.put_line (‘A is big’); Dbms_output.put_line (‘A is big’); End if; ELSIF Dbms_output.put_line (‘B is big’); End if; Downloaded From: http://www.cbseportal.com
  • 5. Downloaded From: http://www.cbseportal.com If A > B Then Dbms_output.put_line (‘A is big’); ELSE Dbms_output.put_line (‘B is big’); End if; Downloaded From: http://www.cbseportal.com