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

Recently uploaded (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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