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

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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?Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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 organizationRadu Cotescu
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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 Scriptwesley chun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Featured

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.pdfmarketingartwork
 
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 2024Neil Kimberley
 
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)contently
 
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 2024Albert Qian
 
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 InsightsKurio // The Social Media Age(ncy)
 
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 2024Search Engine Journal
 
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 summarySpeakerHub
 
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 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 Tessa Mero
 
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 IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
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 managementMindGenius
 
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...RachelPearson36
 
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...Applitools
 
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 WorkGetSmarter
 

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