This document discusses declaring and using variables in PL/SQL blocks. It covers declaring scalar variables like numbers, dates, strings, and booleans. It also discusses composite variables, reference variables, and LOB variables. It explains initializing variables, naming conventions, and using the %TYPE attribute. It describes using DBMS_OUTPUT to display output and bind variables to pass values between PL/SQL and SQL*Plus. The overall goal is to teach how to declare variables, execute blocks, and handle exceptions when programming in PL/SQL.
Oracle - Program with PL/SQL - Lession 03Thuan Nguyen
This document discusses interacting with Oracle Server objects through PL/SQL. It covers:
1. Writing SELECT, DML, and transaction control statements in PL/SQL to extract, modify and manage data.
2. Using implicit cursors and attributes to check outcomes of SQL statements.
3. Best practices for naming conventions to avoid ambiguities between local and database identifiers.
Oracle - Program with PL/SQL - Lession 09Thuan Nguyen
This document discusses procedures in PL/SQL, including:
1. How to create procedures using the CREATE PROCEDURE statement and define parameters.
2. The different parameter modes: IN, OUT, and IN OUT.
3. How to handle exceptions within procedures.
4. How to invoke procedures from other procedures, scripts, or applications.
5. Best practices for developing reusable procedures.
Triggers are stored PL/SQL blocks that are associated with a table, view, schema or database and execute automatically when a triggering event occurs. There are two types of triggers: application triggers that fire on application events and database triggers that fire on data or system events. Triggers can be used to centralize global operations, perform related actions, enforce complex integrity constraints and compute derived values automatically. The timing of a trigger determines whether it executes before or after the triggering event.
This document discusses sample PL/SQL code projects including:
1) Using multiple cursors and parameters to create reports from database tables on regions, countries, and languages.
2) Handling user defined exceptions when querying and deleting from a database table based on condition checks.
3) Creating functions.
4) Creating packages with overloaded procedures.
5) Creating triggers to maintain data integrity where check constraints would be ineffective.
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...rehaniltifat
This document discusses composite data types in PL/SQL including records, collections like index by tables and nested tables, and using explicit cursors. It provides examples of declaring different composite data types like records and index by tables, using %ROWTYPE attribute, and controlling explicit cursors through open, fetch, close operations and cursor attributes. It also discusses using cursors with parameters and FOR UPDATE/WHERE CURRENT OF clauses for locking and updating rows.
This document provides an agenda and overview for a two-day PL/SQL Fundamentals training course. The agenda covers key PL/SQL concepts like language features, the DECLARE, BEGIN, and EXCEPTION clauses, explicit cursors, nested blocks, and declared subprograms. Students will learn to program with PL/SQL using a sample COMPANY database that will be set up on Oracle Database Express Edition. The course is a prerequisite for more advanced PL/SQL trainings.
PACKAGES, Package Specification and Scope, Create Package Syntax, Declaring Procedures and Functions within a Package, Package Body, Create Package Body Syntax,Example –Package, Example– Package Body, Example – Calling Package Procedure, mResults of Calling Package Procedure, Cursors in Packages , cursor Example – Package Body, Example – Use Cursor Variable
Oracle - Program with PL/SQL - Lession 03Thuan Nguyen
This document discusses interacting with Oracle Server objects through PL/SQL. It covers:
1. Writing SELECT, DML, and transaction control statements in PL/SQL to extract, modify and manage data.
2. Using implicit cursors and attributes to check outcomes of SQL statements.
3. Best practices for naming conventions to avoid ambiguities between local and database identifiers.
Oracle - Program with PL/SQL - Lession 09Thuan Nguyen
This document discusses procedures in PL/SQL, including:
1. How to create procedures using the CREATE PROCEDURE statement and define parameters.
2. The different parameter modes: IN, OUT, and IN OUT.
3. How to handle exceptions within procedures.
4. How to invoke procedures from other procedures, scripts, or applications.
5. Best practices for developing reusable procedures.
Triggers are stored PL/SQL blocks that are associated with a table, view, schema or database and execute automatically when a triggering event occurs. There are two types of triggers: application triggers that fire on application events and database triggers that fire on data or system events. Triggers can be used to centralize global operations, perform related actions, enforce complex integrity constraints and compute derived values automatically. The timing of a trigger determines whether it executes before or after the triggering event.
This document discusses sample PL/SQL code projects including:
1) Using multiple cursors and parameters to create reports from database tables on regions, countries, and languages.
2) Handling user defined exceptions when querying and deleting from a database table based on condition checks.
3) Creating functions.
4) Creating packages with overloaded procedures.
5) Creating triggers to maintain data integrity where check constraints would be ineffective.
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...rehaniltifat
This document discusses composite data types in PL/SQL including records, collections like index by tables and nested tables, and using explicit cursors. It provides examples of declaring different composite data types like records and index by tables, using %ROWTYPE attribute, and controlling explicit cursors through open, fetch, close operations and cursor attributes. It also discusses using cursors with parameters and FOR UPDATE/WHERE CURRENT OF clauses for locking and updating rows.
This document provides an agenda and overview for a two-day PL/SQL Fundamentals training course. The agenda covers key PL/SQL concepts like language features, the DECLARE, BEGIN, and EXCEPTION clauses, explicit cursors, nested blocks, and declared subprograms. Students will learn to program with PL/SQL using a sample COMPANY database that will be set up on Oracle Database Express Edition. The course is a prerequisite for more advanced PL/SQL trainings.
PACKAGES, Package Specification and Scope, Create Package Syntax, Declaring Procedures and Functions within a Package, Package Body, Create Package Body Syntax,Example –Package, Example– Package Body, Example – Calling Package Procedure, mResults of Calling Package Procedure, Cursors in Packages , cursor Example – Package Body, Example – Use Cursor Variable
Triggers are stored programs that are automatically executed in response to events like data manipulation language (DML) statements or database definition language (DDL) statements. They can be used for purposes like enforcing referential integrity, auditing, and event logging. The syntax to create a trigger includes keywords like BEFORE, AFTER, INSTEAD OF to specify when it should be executed in relation to a triggering statement. PL/SQL packages are used to group related logic, types, variables and subprograms. A package has a specification that declares its elements and a body that defines them. Packages provide a way to encapsulate and organize code.
This document provides an overview of executable statements in PL/SQL blocks. It discusses lexical units like identifiers, delimiters, and literals. It describes PL/SQL block syntax and guidelines for writing executable code. It also covers commenting code, using SQL functions, data type conversion, and nested blocks. The document provides examples and best practices for writing readable and maintainable PL/SQL code.
Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...Carlos Sierra
Adaptive Cursor Sharing (ACS) is a feature available since 11g. It is enabled by default. ACS can help to generate multiple non-persistent Optimal Execution Plans for a given SQL. But it requires a sequence of events for it to get truly activated. This presentation describes what is ACS, when it is used and when it is not. Then it demonstrates ACS capabilities and limitations with a live demo.
This session is about: How Adaptive Cursor Sharing (ACS) actually works. How a bind sensitive cursor becomes bind aware. What are those "ACS buckets". How the "Selectivity Profile" works. Why sometimes your SQL becomes bind aware and why sometimes it does not. How is that ACS interacts with SQL Plan Management (SPM). These and other questions about ACS are answered in detail.
Some live demonstrations are used to illustrate the ramp-up process on ACS and how some child cursors are created then flagged as non-shareable. You will also "see" how the ACS Selectivity Profile is adapted as new executions make use of predicates with new Selectivities. ACS promotes Plan Flexibility while SPM promotes Plan Stability. Understanding how these duo interacts becomes of great value when some gentle intervention is needed to restore this delicate balance.
This session is for those Developers and DBAs that "need" to understand how things work. ACS can be seen as a back-box; or you can "look" inside and understand how it actually works. If you are curious about the ACS functionality, then this Session brings some light. Consider this session only if you are pretty familiar with Cursor Sharing, Binds, Plan Stability and Plan Flexibility.
This document discusses database triggers in Oracle, including:
- Database triggers fire on data events like DML or system events like logon and can be used to centralize operations or perform related actions.
- Triggers can be defined to fire before, after or instead of triggering events and can be statement triggers that fire once per statement or row triggers that fire once per row.
- Examples are provided for creating triggers that validate data, audit changes, and derive values from other columns.
- Special trigger variables like :NEW and :OLD allow access to old and new row values in row triggers.
This document provides an introduction to structured query language (SQL). It outlines the objectives of learning SQL, which are to use SQL for data administration and data manipulation. The agenda covers SQL concepts like data types, constraints, database relationships, queries, and commands. It discusses SQL database objects and how to retrieve, customize, group and join data. It also covers inserting, updating, deleting data and working with tables, views, constraints, stored procedures and functions.
SQL is a standard language for querying and manipulating data in relational databases. It contains five categories of statements: data definition language (DDL) for defining data structure, data manipulation language (DML) for managing data, data control language (DCL) for privileges, transaction control statements for transactions, and session control statements for sessions. Common DDL commands include CREATE, ALTER, and DROP for databases and tables. Common DML commands include SELECT, INSERT, UPDATE, and DELETE for querying and modifying data. Joins are used to combine data from two or more tables.
PL/SQL is a combination of SQL and procedural languages that enhances SQL's capabilities. It allows processing of SQL statements as a block. A PL/SQL block consists of optional declaration, mandatory execution, and optional exception sections. Variables, constants, records can be declared in the declaration section and used in the execution section. The execution section contains the main program logic. Exceptions are handled in the exception section. PL/SQL supports programming constructs like conditional statements and loops.
PL/SQL is a block-structured language used for accessing and manipulating Oracle databases. A PL/SQL block contains three parts: a declarative section, executable section, and exception-handling section. PL/SQL supports both scalar and composite datatypes. Control structures include conditional statements like IF-THEN-ELSE and CASE, and iterative statements like LOOP, WHILE, and FOR. Database interaction is done through SQL statements and cursors, which allow processing of multiple rows returned from a query.
PL/SQL is Oracle's standard language for accessing and manipulating data in Oracle databases. It allows developers to integrate SQL statements with procedural constructs like variables, conditions, and loops. PL/SQL code is organized into blocks that define a declarative section for variable declarations and an executable section containing SQL and PL/SQL statements. Variables can be scalar, composite, reference, or LOB types and are declared in the declarative section before being used in the executable section.
What is PL/SQL
Procedural Language – SQL
An extension to SQL with design features of programming languages (procedural and object oriented)
PL/SQL and Java are both supported as internal host languages within Oracle products.
This document provides an introduction to PL/SQL, including:
- PL/SQL allows for variables, loops, functions, and easier integration of SQL code for improved performance.
- Code is organized into anonymous blocks with a declare, begin, and exception section.
- It describes data types, variables, bind variables, substitution variables, and how to declare variables based on table columns or rows.
- The goal is to explain the basic structure and capabilities of PL/SQL to allow for more complex programming within Oracle databases.
Clauses in Sql(Structured Query Language), distinct clause, where clause, where clause, order by clause, group by clause, having clause, Relational Database Management System
This document provides an overview of C# programming basics, including:
- C# is an object-oriented language where the basic unit is a class containing methods and variables.
- A C# program consists of at least one class that must contain a Main method, which acts as the program entry point.
- The document discusses basic C# concepts like variables, data types, operators, conditional statements, loops, methods, and arrays.
- It also covers how to compile and run a simple "Hello World" C# program, and provides examples of different programming constructs.
Este documento presenta varias optimizaciones avanzadas para SQL Server, incluyendo configuraciones de NUMA, hilos, máscaras de afinidad de E/S, grado máximo de paralelismo y configuración de memoria. También cubre configuraciones avanzadas de base de datos como registros de transacciones, optimización de correlación de fecha y parametrización. Finalmente, presenta patrones para desarrolladores sobre el uso de parámetros de tabla y mejoras en el uso de funciones en SQL Server.
11 Understanding and Influencing the PL/SQL Compilarrehaniltifat
This document discusses normalization of a sales tax invoice database. It begins by showing an initial sales tax invoice table that is not normalized. It then shows the tables after normalization into first normal form (1NF), second normal form (2NF), and third normal form (3NF). The normalized tables separate the data into tables for the invoice, buyer, product, tax, and price details.
Consists of the explanations of the basics of SQL and commands of SQL.Helpful for II PU NCERT students and also degree studeents to understand some basic things.
This document discusses several database objects in Oracle: sequences, indexes, and synonyms. Sequences are used to automatically generate unique primary key values. Indexes improve query performance by indexing columns. Synonyms provide alternative names for objects to simplify access. The document provides examples of creating, modifying, confirming, and removing these database objects through SQL statements.
PL/SQL is a combination of SQL along with the procedural features of programming languages.
It provides specific syntax for this purpose and supports exactly the same datatypes as SQL.
Oracle - Program with PL/SQL - Lession 10Thuan Nguyen
Functions allow users to define reusable blocks of code that can return values. Functions are created using the CREATE FUNCTION syntax and return a single value. They can be invoked from SQL statements and PL/SQL code. Functions must contain a RETURN statement and only accept parameters and return types that are valid SQL data types. Procedures are similar but do not return values and are used to perform actions rather than compute values.
Oracle - Program with PL/SQL - Lession 18Thuan Nguyen
This document discusses managing dependencies between database objects like tables, views, and stored procedures. It describes how to track dependencies, understand the effects of changing objects on procedures, and manage recompilation when dependencies change. Local dependencies within a schema and remote dependencies between schemas are covered. The document provides examples of dependency scenarios and recommends practices like declaring variables and records by type to minimize dependency failures during recompilation.
Triggers are stored programs that are automatically executed in response to events like data manipulation language (DML) statements or database definition language (DDL) statements. They can be used for purposes like enforcing referential integrity, auditing, and event logging. The syntax to create a trigger includes keywords like BEFORE, AFTER, INSTEAD OF to specify when it should be executed in relation to a triggering statement. PL/SQL packages are used to group related logic, types, variables and subprograms. A package has a specification that declares its elements and a body that defines them. Packages provide a way to encapsulate and organize code.
This document provides an overview of executable statements in PL/SQL blocks. It discusses lexical units like identifiers, delimiters, and literals. It describes PL/SQL block syntax and guidelines for writing executable code. It also covers commenting code, using SQL functions, data type conversion, and nested blocks. The document provides examples and best practices for writing readable and maintainable PL/SQL code.
Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...Carlos Sierra
Adaptive Cursor Sharing (ACS) is a feature available since 11g. It is enabled by default. ACS can help to generate multiple non-persistent Optimal Execution Plans for a given SQL. But it requires a sequence of events for it to get truly activated. This presentation describes what is ACS, when it is used and when it is not. Then it demonstrates ACS capabilities and limitations with a live demo.
This session is about: How Adaptive Cursor Sharing (ACS) actually works. How a bind sensitive cursor becomes bind aware. What are those "ACS buckets". How the "Selectivity Profile" works. Why sometimes your SQL becomes bind aware and why sometimes it does not. How is that ACS interacts with SQL Plan Management (SPM). These and other questions about ACS are answered in detail.
Some live demonstrations are used to illustrate the ramp-up process on ACS and how some child cursors are created then flagged as non-shareable. You will also "see" how the ACS Selectivity Profile is adapted as new executions make use of predicates with new Selectivities. ACS promotes Plan Flexibility while SPM promotes Plan Stability. Understanding how these duo interacts becomes of great value when some gentle intervention is needed to restore this delicate balance.
This session is for those Developers and DBAs that "need" to understand how things work. ACS can be seen as a back-box; or you can "look" inside and understand how it actually works. If you are curious about the ACS functionality, then this Session brings some light. Consider this session only if you are pretty familiar with Cursor Sharing, Binds, Plan Stability and Plan Flexibility.
This document discusses database triggers in Oracle, including:
- Database triggers fire on data events like DML or system events like logon and can be used to centralize operations or perform related actions.
- Triggers can be defined to fire before, after or instead of triggering events and can be statement triggers that fire once per statement or row triggers that fire once per row.
- Examples are provided for creating triggers that validate data, audit changes, and derive values from other columns.
- Special trigger variables like :NEW and :OLD allow access to old and new row values in row triggers.
This document provides an introduction to structured query language (SQL). It outlines the objectives of learning SQL, which are to use SQL for data administration and data manipulation. The agenda covers SQL concepts like data types, constraints, database relationships, queries, and commands. It discusses SQL database objects and how to retrieve, customize, group and join data. It also covers inserting, updating, deleting data and working with tables, views, constraints, stored procedures and functions.
SQL is a standard language for querying and manipulating data in relational databases. It contains five categories of statements: data definition language (DDL) for defining data structure, data manipulation language (DML) for managing data, data control language (DCL) for privileges, transaction control statements for transactions, and session control statements for sessions. Common DDL commands include CREATE, ALTER, and DROP for databases and tables. Common DML commands include SELECT, INSERT, UPDATE, and DELETE for querying and modifying data. Joins are used to combine data from two or more tables.
PL/SQL is a combination of SQL and procedural languages that enhances SQL's capabilities. It allows processing of SQL statements as a block. A PL/SQL block consists of optional declaration, mandatory execution, and optional exception sections. Variables, constants, records can be declared in the declaration section and used in the execution section. The execution section contains the main program logic. Exceptions are handled in the exception section. PL/SQL supports programming constructs like conditional statements and loops.
PL/SQL is a block-structured language used for accessing and manipulating Oracle databases. A PL/SQL block contains three parts: a declarative section, executable section, and exception-handling section. PL/SQL supports both scalar and composite datatypes. Control structures include conditional statements like IF-THEN-ELSE and CASE, and iterative statements like LOOP, WHILE, and FOR. Database interaction is done through SQL statements and cursors, which allow processing of multiple rows returned from a query.
PL/SQL is Oracle's standard language for accessing and manipulating data in Oracle databases. It allows developers to integrate SQL statements with procedural constructs like variables, conditions, and loops. PL/SQL code is organized into blocks that define a declarative section for variable declarations and an executable section containing SQL and PL/SQL statements. Variables can be scalar, composite, reference, or LOB types and are declared in the declarative section before being used in the executable section.
What is PL/SQL
Procedural Language – SQL
An extension to SQL with design features of programming languages (procedural and object oriented)
PL/SQL and Java are both supported as internal host languages within Oracle products.
This document provides an introduction to PL/SQL, including:
- PL/SQL allows for variables, loops, functions, and easier integration of SQL code for improved performance.
- Code is organized into anonymous blocks with a declare, begin, and exception section.
- It describes data types, variables, bind variables, substitution variables, and how to declare variables based on table columns or rows.
- The goal is to explain the basic structure and capabilities of PL/SQL to allow for more complex programming within Oracle databases.
Clauses in Sql(Structured Query Language), distinct clause, where clause, where clause, order by clause, group by clause, having clause, Relational Database Management System
This document provides an overview of C# programming basics, including:
- C# is an object-oriented language where the basic unit is a class containing methods and variables.
- A C# program consists of at least one class that must contain a Main method, which acts as the program entry point.
- The document discusses basic C# concepts like variables, data types, operators, conditional statements, loops, methods, and arrays.
- It also covers how to compile and run a simple "Hello World" C# program, and provides examples of different programming constructs.
Este documento presenta varias optimizaciones avanzadas para SQL Server, incluyendo configuraciones de NUMA, hilos, máscaras de afinidad de E/S, grado máximo de paralelismo y configuración de memoria. También cubre configuraciones avanzadas de base de datos como registros de transacciones, optimización de correlación de fecha y parametrización. Finalmente, presenta patrones para desarrolladores sobre el uso de parámetros de tabla y mejoras en el uso de funciones en SQL Server.
11 Understanding and Influencing the PL/SQL Compilarrehaniltifat
This document discusses normalization of a sales tax invoice database. It begins by showing an initial sales tax invoice table that is not normalized. It then shows the tables after normalization into first normal form (1NF), second normal form (2NF), and third normal form (3NF). The normalized tables separate the data into tables for the invoice, buyer, product, tax, and price details.
Consists of the explanations of the basics of SQL and commands of SQL.Helpful for II PU NCERT students and also degree studeents to understand some basic things.
This document discusses several database objects in Oracle: sequences, indexes, and synonyms. Sequences are used to automatically generate unique primary key values. Indexes improve query performance by indexing columns. Synonyms provide alternative names for objects to simplify access. The document provides examples of creating, modifying, confirming, and removing these database objects through SQL statements.
PL/SQL is a combination of SQL along with the procedural features of programming languages.
It provides specific syntax for this purpose and supports exactly the same datatypes as SQL.
Oracle - Program with PL/SQL - Lession 10Thuan Nguyen
Functions allow users to define reusable blocks of code that can return values. Functions are created using the CREATE FUNCTION syntax and return a single value. They can be invoked from SQL statements and PL/SQL code. Functions must contain a RETURN statement and only accept parameters and return types that are valid SQL data types. Procedures are similar but do not return values and are used to perform actions rather than compute values.
Oracle - Program with PL/SQL - Lession 18Thuan Nguyen
This document discusses managing dependencies between database objects like tables, views, and stored procedures. It describes how to track dependencies, understand the effects of changing objects on procedures, and manage recompilation when dependencies change. Local dependencies within a schema and remote dependencies between schemas are covered. The document provides examples of dependency scenarios and recommends practices like declaring variables and records by type to minimize dependency failures during recompilation.
Oracle - Program with PL/SQL - Lession 04Thuan Nguyen
This document discusses control structures in PL/SQL including IF statements, CASE expressions, and loops. It provides examples of using IF-THEN-ELSE statements and IF-THEN-ELSIF statements to conditionally execute code. It also demonstrates using basic, WHILE, and FOR loops to iteratively execute code. Guidelines are provided for using control structures and nested loops with labels.
Oracle - Program with PL/SQL - Lession 07Thuan Nguyen
1. Cursors can be declared with parameters to return different active sets each time the cursor is opened. Parameters allow filtering the cursor result set.
2. The FOR UPDATE clause locks rows before updating or deleting them using a cursor. It is required when updating or deleting the current row referenced by the WHERE CURRENT OF clause.
3. The WHERE CURRENT OF clause references the current row of an explicit cursor and is used with the FOR UPDATE clause to update or delete the row currently being processed by the cursor.
Oracle - Program with PL/SQL - Lession 02Thuan Nguyen
- The document describes the syntax and guidelines for writing executable PL/SQL blocks, including using identifiers correctly, writing statements in the executable section, and nested block structure. It also covers data type conversions, functions, operators, and programming conventions.
- Key aspects are declaring and scoping variables, writing nested blocks, using functions like TO_DATE for data type conversions, and following conventions for readability like indentation and commenting.
- The goal is for readers to understand how to structure PL/SQL code, including blocks and statements, handle data types, and write maintainable code.
Oracle - Program with PL/SQL - Lession 11Thuan Nguyen
This document discusses managing subprograms and stored PL/SQL objects. It contrasts system privileges with object privileges and invoker's rights with definers rights. It also describes using data dictionary views like USER_OBJECTS, USER_SOURCE, and USER_ERRORS to manage and debug stored objects. The DBMS_OUTPUT package is identified as a way to debug subprograms by accumulating output in a buffer and allowing retrieval of the information.
Oracle - Program with PL/SQL - Lession 05Thuan Nguyen
This document discusses composite data types in PL/SQL including records, INDEX BY tables, and tables of records. It provides examples of how to create each type, use the %ROWTYPE attribute to define records based on database tables, and demonstrates various methods for accessing and manipulating data in INDEX BY tables including COUNT, EXISTS, DELETE and TRIM. The key concepts covered are how to define and work with composite data structures in PL/SQL to efficiently retrieve and process sets of related data.
Oracle - Program with PL/SQL - Lession 12Thuan Nguyen
This document discusses packages in PL/SQL and how to create them. The main points are:
1. Packages are used to group logically related program units like procedures, functions, variables, etc. They have a specification and body.
2. The specification declares public elements and is used to interface with the package. The body defines private and public elements and implements the specification.
3. To create a package, use the CREATE OR REPLACE PACKAGE statement for the specification and CREATE OR REPLACE PACKAGE BODY for the body. Public elements can then be invoked from outside the package.
4. Packages improve organization, security, performance and allow hiding implementation details in the body. Elements
Oracle - Program with PL/SQL - Lession 14Thuan Nguyen
This document provides an overview of several Oracle-supplied packages including DBMS_SQL, DBMS_DDL, DBMS_JOB, UTL_FILE, UTL_HTTP, and UTL_TCP. It describes how these packages can be used to write dynamic SQL, schedule jobs, generate text reports by writing to files, and make HTTP requests. The key goals are to enable extended database functionality and access to restricted SQL features from PL/SQL code. Specific functions and procedures of each package are demonstrated through examples.
Oracle - Program with PL/SQL - Lession 16Thuan Nguyen
This document describes how to create and use database triggers in Oracle. It discusses the different types of triggers, how to create triggers for DML statements and views, and how to manage triggers. Key points include:
- Triggers can be defined to fire before or after DML statements or instead of DML on views.
- Row triggers fire once per row affected, statement triggers fire once per statement.
- Triggers use OLD and NEW qualifiers to access old and new row values.
- INSTEAD OF triggers on views perform DML instead of the triggering statement.
- Triggers must be carefully tested to avoid unintended consequences.
Oracle - Program with PL/SQL - Lession 15Thuan Nguyen
This document discusses managing large objects (LOBs) in Oracle databases. It compares LOB and LONG data types, describes internal and external LOBs, and explains how to use the DBMS_LOB package to create, populate, and interact with LOB columns. Key topics covered include the four LOB data types (BLOB, CLOB, NCLOB, BFILE), using the DBMS_LOB package to read and write LOBs, and creating temporary LOBs for transformations.
Oracle - Program with PL/SQL - Lession 13Thuan Nguyen
This document discusses various concepts related to packages in PL/SQL, including overloading subprograms, using forward declarations, creating one-time initialization procedures, and controlling the persistent state of package variables and cursors. It provides examples of overloading procedures and functions, using forward references, and creating packages with table and record types. The objectives are to write packages that use overloading, describe errors from mutually recursive subprograms, initialize variables with one-time procedures, and identify persistent package states.
Oracle - Program with PL/SQL - Lession 06Thuan Nguyen
This document discusses explicit cursors in PL/SQL. It covers:
1) Declaring explicit cursors to query rows from a table and control the cursor through opening, fetching, and closing.
2) Using cursor attributes to check the status and number of rows fetched.
3) Processing cursor rows using a cursor FOR loop or fetching into a record variable.
Oracle - Program with PL/SQL - Lession 17Thuan Nguyen
This document discusses advanced concepts for creating and using database triggers in Oracle. It covers creating triggers on DDL statements, system events, and tables. Triggers can be used to enforce security, data integrity, referential integrity, event logging, and compute derived values. The document provides examples of triggers for these purposes and discusses best practices for managing triggers.
Oracle - Program with PL/SQL - Lession 08Thuan Nguyen
This document discusses handling exceptions in PL/SQL. It defines exceptions as identifiers raised during execution due to Oracle errors or being explicitly raised. Exceptions can be trapped with handlers or propagated. There are predefined Oracle exceptions as well as user-defined exceptions. Handlers use an EXCEPTION WHEN clause and can trap specific or all exceptions. Functions like SQLCODE and SQLERRM provide error details. The RAISE_APPLICATION_ERROR procedure issues user errors. Exceptions propagate to calling environments if unhandled.
The document provides an overview and introduction to SQL and PL/SQL. It discusses the main SQL statements including SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, COMMIT, ROLLBACK, and GRANT. It also describes the main tables that will be used in the course, including the EMP and DEPT tables. Finally, it demonstrates basic SELECT statements to retrieve data from tables and how to select specific columns or all columns.
PL/SQL is a combination of SQL along with procedural programming features. It allows developers to perform operations on data in an Oracle database such as querying, inserting, updating, and deleting. Some key PL/SQL concepts include variables, conditions, loops, exceptions, triggers, stored procedures, and cursors. Cursors allow a program to retrieve multiple rows from a SQL statement and process them one by one.
This document provides a lesson on using SQL SELECT statements to retrieve data from database tables. It covers the basic SELECT statement syntax, selecting specific columns, column aliases, arithmetic expressions, NULL values, concatenation operators, literal strings, the DISTINCT keyword, and using the DESCRIBE command to view table structures. The objectives are to be able to list the capabilities of SQL SELECT statements and execute a basic SELECT statement.
The document provides an introduction and overview of SQL procedural language (PL/SQL) programming. It discusses basic PL/SQL concepts like declaring variables, conditional statements using IF/ELSEIF, loops using LOOP and WHILE, and exception handling. Examples are given for selecting, inserting, updating and displaying data using PL/SQL blocks. The document is meant as a tutorial for learning the basic structure and functionality of PL/SQL.
This document provides an introduction to PL/SQL, including PL/SQL block structure, data types, variables, control structures, and more. PL/SQL combines procedural language elements with SQL statements to enhance database programming capabilities. Key elements include DECLARE, BEGIN, and END sections in a PL/SQL block; data types like NUMBER, VARCHAR2, DATE; variables and constants; control structures like IF-THEN-ELSE; and functions for output.
The document provides examples of SQL statements used to create database objects like tables, users, schemas, procedures, and triggers in Oracle/PLSQL. It includes the CREATE statements to create a database, tablespace, user, schema, procedure, function, role, and trigger. It also includes examples of GRANT, REVOKE, and ALTER statements to manage privileges and roles.
PL/SQL is a procedural language designed specifically to embrace SQL statements within its syntax. PL/SQL program units are compiled by the Oracle Database server and stored inside the database.
The document provides instructions for connecting to an Oracle database and completing several labs on Oracle concepts like subqueries, indexes, data dictionary, concurrency, schema objects, and table partitioning. It includes SQL examples and steps to create views, procedures, functions, triggers, and partitioned tables using techniques like list, range, and hash partitioning. The labs cover important Oracle topics to help learn how to optimize queries, understand the database metadata, handle concurrency issues, and partition tables for improved performance.
The document discusses stored procedures and embedded SQL. Stored procedures allow functions to be stored on the database server and reduce network traffic by being invoked multiple times. They can be written in languages like SQL, C, or Java. Embedded SQL is used to interface SQL with a host programming language by embedding SQL statements directly into program code using syntax like EXEC SQL.
PL/SQL is a database-oriented programming language that extends SQL with procedural capabilities like condition checking, looping, and branching. It allows programmers to handle errors and display user-friendly error messages. PL/SQL code is organized into declarative regions, and it can define variables, constants, cursors, procedures, and functions. Cursors are used to process result sets from a SQL query row by row.
The document contains examples of PL/SQL blocks and procedures to perform various operations like checking if a year is a leap year, calculating employee bonuses based on salary, retrieving employee data using cursors, updating job titles in a package, and validating department IDs when adding new employees. It demonstrates how to write PL/SQL code to query and manipulate database tables, handle exceptions, define functions and procedures, and group related code into packages.
This document provides an introduction to PL/SQL, including what PL/SQL is, why it is used, its basic structure and components like blocks, variables, and types. It also covers key PL/SQL concepts like conditions, loops, cursors, stored procedures, functions, and triggers. Examples are provided to illustrate how to write and execute basic PL/SQL code blocks, programs with variables, and stored programs that incorporate cursors, exceptions, and other features.
The document provides an overview of PL/SQL and server-side database programming. It discusses:
1) What PL/SQL is and how it extends SQL with programming features like variables, loops, and conditionals to allow for procedural logic on the server-side.
2) The advantages of server-side programming using PL/SQL over client-side programming, including improved performance due to reduced network traffic and ability to reuse code.
3) Key PL/SQL concepts like blocks, data types, scope rules, operators, program flow control structures, exceptions, and subprograms like procedures and functions.
This document discusses various ways to customize SQL*Plus and produce more readable output, including:
1) Using substitution variables to prompt for input and dynamically alter queries, reports, and file names.
2) Defining variables with DEFINE and ACCEPT and passing values between SQL statements.
3) Customizing the SQL*Plus environment with SET commands and verifying settings with SHOW.
This document provides an overview of PL/SQL including:
- PL/SQL block structure with declare, execution, and exception sections
- Variables, constants, datatypes
- Control structures like IF/ELSE statements and loop structures
- Procedures and functions
- Uses of PL/SQL include combining SQL with procedural logic, writing reusable code, and handling exceptions.
PL/SQL is a combination of SQL and procedural programming languages. It allows developers to perform operations like control flow statements, variable declarations, and exception handling. PL/SQL code is organized into blocks that contain a declarative part, an executable part, and an optional exception-handling part. Variables and other objects can be declared locally or globally depending on their scope. Control structures like IF-THEN-ELSE, CASE, and loops allow conditional and iterative execution. Procedures and functions can also be created to reuse code.
e computer notes - Producing readable output with i sql plusecomputernotes
The document discusses how to produce readable output using iSQL*Plus, including using substitution variables, customizing the environment, and formatting output with commands like COLUMN, BREAK, TTITLE, and BTITLE. It also covers creating script files to run reports.
DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
DBA Commands and Concepts That Every Developer Should Know was presented by Alex Zaballa, an Oracle DBA with experience in Brazil and Angola. The presentation covered Oracle Flashback Query, Flashback Table, RMAN table recovery, pending statistics, explain plan, DBMS_APPLICATION_INFO, row-by-row vs bulk processing, Virtual Private Database, extended data types, SQL text expansion, identity columns, UTL_CALL_STACK, READ privileges vs SELECT privileges, and online table redefinition. The presentation included demonstrations of many of these concepts.
This document discusses different types of joins in SQL, including:
1) Equijoins to retrieve records that match between two tables using column equality.
2) Nonequijoins using operators like BETWEEN to join on non-equal columns.
3) Outer joins to return both matching and non-matching record results from the left or right tables.
4) Self-joins to join a table to itself.
5) Cross joins to generate the Cartesian product between two tables without a join condition.
This document discusses embedded SQL, functions, procedures, and triggers. Embedded SQL allows SQL statements to be embedded within host languages like C/C++ and Java. Functions and procedures can be written in SQL or an external language and used to perform calculations on data. Triggers are stored programs that automatically execute in response to data changes or other events. The document provides examples of how to create and use these database objects to query and manipulate data.
MySQL is an open-source relational database management system that uses SQL and runs a server providing multi-user access to databases. It allows users to perform queries and make changes to data through commands like SELECT, INSERT, UPDATE, DELETE. Stored procedures and functions allow users to write and save blocks of SQL code for repeated execution with consistent results.
This document discusses stored procedures in databases. It provides an overview of stored procedures, their advantages like reduced network traffic, and how they allow local variables, loops, and examination of data tuples. It describes how to write stored procedures using languages like SQL, including declaring parameters, and provides examples of stored procedures using conditional statements, loops, and cursors to process data.
The document provides an overview of various Oracle tips and tricks, including CASE statements, joins, timestamps, renaming tables/columns, merge statements, subqueries, window functions, hierarchical queries, XML, grouping sets, rollups and cubes, indexes, temporary tables and more. Key features introduced in Oracle 9i such as the CASE statement, full outer joins, timestamps and the WITH clause are highlighted.
Similar to Oracle - Program with PL/SQL - Lession 01 (20)
34. VARIABLE g_monthly_sal NUMBER SET VERIFY OFF DECLARE v_sal NUMBER(9,2) := &p_annual_sal; BEGIN :g_monthly_sal := v_sal/12; END; / PRINT g_monthly_sal
35.
36.
37.
38.
39.
Editor's Notes
Schedule: Timing Topic 40 minutes Lecture 25 minutes Practice 65 minutes Total
Lesson Aim This lesson presents the basic rules and structure for writing and executing PL/SQL blocks of code. It also shows you how to declare variables and assign data types to them.
PL/SQL Block Structure PL/SQL is a block-structured language, meaning that programs can be divided into logical blocks. A PL/SQL block consists of up to three sections: declarative (optional), executable (required), and exception handling (optional). The following table describes the three sections: Section Description Inclusion Declarative Contains all variables, constants, cursors, and user-defined exceptions that are referenced in the executable and declarative sections Optional Executable Contains SQL statements to manipulate data in the database and PL/SQL statements to manipulate data in the block Mandatory Exception handling Specifies the actions to perform when errors and abnormal conditions arise in the executable section Optional
Executing Statements and PL/SQL Blocks • Place a semicolon (;) at the end of a SQL statement or PL/SQL control statement. • When the block is executed successfully, without unhandled errors or compile errors, the message output should be as follows: • Section keywords DECLARE, BEGIN, and EXCEPTION are not followed by semicolons. • END and all other PL/SQL statements require a semicolon to terminate the statement. • You can string statements together on the same line, but this method is not recommended for clarity or editing. Note: In PL/SQL, an error is called an exception . With modularity you can break an application down into manageable, well-defined modules. Through successive refinement, you can reduce a complex problem to a set of simple problems that have easyto- implement solutions. PL/SQL meets this need with program units, which include blocks, subprograms, and packages.
Lesson Aim To extract data from the database, you need to use the structured query language ( SQL ) SELECT statement. You may need to restrict the columns that are displayed. This lesson describes all the SQL statements needed to perform these actions. You may want to create SELECT statements that can be used more than once. This lesson also covers the i SQL*Plus environment where you execute SQL statements. Note: i SQL*Plus is new in the Oracle9 i product. It is a browser environment where you execute SQL commands. In prior releases of Oracle, SQL*Plus was the default environment where you executed SQL commands. SQL*Plus is still available and is described in Appendix C.
Lesson Aim To extract data from the database, you need to use the structured query language ( SQL ) SELECT statement. You may need to restrict the columns that are displayed. This lesson describes all the SQL statements needed to perform these actions. You may want to create SELECT statements that can be used more than once. This lesson also covers the i SQL*Plus environment where you execute SQL statements. Note: i SQL*Plus is new in the Oracle9 i product. It is a browser environment where you execute SQL commands. In prior releases of Oracle, SQL*Plus was the default environment where you executed SQL commands. SQL*Plus is still available and is described in Appendix C.
Block Types A PL/SQL program comprises one or more blocks. These blocks can be entirely separate or nested one within another. The basic units (procedures and functions, also known as subprograms, and anonymous blocks) that make up a PL/SQL program are logical blocks, which can contain any number of nested subblocks. Therefore, one block can represent a small part of another block, which in turn can be part of the whole unit of code. Anonymous Blocks Anonymous blocks are unnamed blocks. They are declared at the point in an application where they are to be executed and are passed to the PL/SQL engine for execution at run time. You can embed an anonymous block within a precompiler program and within i SQL*Plus or Server Manager. Triggers in Oracle Developer components consist of such blocks. Subprograms Subprograms are named PL/SQL blocks that can accept parameters and can be invoked. You can declare them either as procedures or as functions. Generally use a procedure to perform an action and a function to compute a value. You can store subprograms at the server or application level. Using Oracle Developer components (Forms, Reports, and Graphics), you can declare procedures and functions as part of the application (a form or report) and call them from other procedures, functions, and triggers (see next page) within the same application whenever necessary. Note: A function is similar to a procedure, except that a function must return a value.
Lesson Aim To extract data from the database, you need to use the structured query language ( SQL ) SELECT statement. You may need to restrict the columns that are displayed. This lesson describes all the SQL statements needed to perform these actions. You may want to create SELECT statements that can be used more than once. This lesson also covers the i SQL*Plus environment where you execute SQL statements. Note: i SQL*Plus is new in the Oracle9 i product. It is a browser environment where you execute SQL commands. In prior releases of Oracle, SQL*Plus was the default environment where you executed SQL commands. SQL*Plus is still available and is described in Appendix C.
Lesson Aim To extract data from the database, you need to use the structured query language ( SQL ) SELECT statement. You may need to restrict the columns that are displayed. This lesson describes all the SQL statements needed to perform these actions. You may want to create SELECT statements that can be used more than once. This lesson also covers the i SQL*Plus environment where you execute SQL statements. Note: i SQL*Plus is new in the Oracle9 i product. It is a browser environment where you execute SQL commands. In prior releases of Oracle, SQL*Plus was the default environment where you executed SQL commands. SQL*Plus is still available and is described in Appendix C.
Lesson Aim To extract data from the database, you need to use the structured query language ( SQL ) SELECT statement. You may need to restrict the columns that are displayed. This lesson describes all the SQL statements needed to perform these actions. You may want to create SELECT statements that can be used more than once. This lesson also covers the i SQL*Plus environment where you execute SQL statements. Note: i SQL*Plus is new in the Oracle9 i product. It is a browser environment where you execute SQL commands. In prior releases of Oracle, SQL*Plus was the default environment where you executed SQL commands. SQL*Plus is still available and is described in Appendix C.
Program Constructs The following table outlines a variety of different PL/SQL program constructs that use the basic PL/SQL block. The program constructs are available based on the environment in which they are executed. Program Construct Description Availability Anonymous blocks Unnamed PL/SQL blocks that are embedded within an application or are issued interactively All PL/SQL environments Application procedures or functions Named PL/SQL blocks stored in an Oracle Forms Developer application or shared library; can accept parameters and can be invoked repeatedly by name Oracle Developer tools components, for example, Oracle Forms Developer, Oracle Reports Stored procedures or functions Named PL/SQL blocks stored in the Oracle server; can accept parameters and can be invoked repeatedly by name Oracle server Packages (Application or Stored) Named PL/SQL modules that group related procedures, functions, and identifiers Oracle server and Oracle Developer tools components, for example, Oracle Forms Developer Database triggers PL/SQL blocks that are associated with a database table and fired automatically when triggered by DML statements Oracle server Application triggers PL/SQL blocks that are associated with an application event and fired automatically Oracle Developer tools components, for example, Oracle Forms Developer Object types User-defined composite data types that encapsulate a data structure along with the functions and procedures needed to manipulate the data Oracle server and Oracle Developer tools …
Use of Variables With PL/SQL you can declare variables and then use them in SQL and procedural statements anywhere that an expression can be used. Variables can be used for the following: • Temporary storage of data: Data can be temporarily stored in one or more variables for use when validating data input and for processing later in the data flow process. • Manipulation of stored values: Variables can be used for calculations and other data manipulations without accessing the database. • Reusability: After they are declared, variables can be used repeatedly in an application simply by referencing them in other statements, including other declarative statements. • Ease of maintenance: When using %TYPE and %ROWTYPE (more information on %ROWTYPE is covered in a subsequent lesson), you declare variables, basing the declarations on the definitions of database columns. If an underlying definition changes, the variable declaration changes accordingly at run time. This provides data independence, reduces maintenance costs, and allows programs to adapt as the database changes to meet new business needs. More information on %TYPE is covered later in this lesson.
Handling Variables in PL/SQL Declare and Initialize Variables in the Declaration Section You can declare variables in the declarative part of any PL/SQL block, subprogram, or package. Declarations allocate storage space for a value, specify its data type, and name the storage location so that you can reference it. Declarations can also assign an initial value and impose the NOT NULL constraint on the variable. Forward references are not allowed. You must declare a variable before referencing it in other statements, including other declarative statements. Assign New Values to Variables in the Executable Section In the executable section, the existing value of the variable is replaced with the new value that is assigned to the variable. Pass Values Into PL/SQL Subprograms Through Parameters There are three parameter modes, IN (the default), OUT, and IN OUT. Use the IN parameter to pass values to the subprogram being called. Use the OUT parameter to return values to the caller of a subprogram. And use the IN OUT parameter to pass initial values to the subprogram being called and to return updated values to the caller. We pass values into anonymous block via i SQL*PLUS substitution variables. Note: Viewing the results from a PL/SQL block through output variables is discussed later in the lesson. …
Types of Variables All PL/SQL variables have a data type, which specifies a storage format, constraints, and valid range of values. PL/SQL supports four data type categories—scalar, composite, reference, and LOB (large object)—that you can use for declaring variables, constants, and pointers. • Scalar data types hold a single value. The main data types are those that correspond to column types in Oracle server tables; PL/SQL also supports Boolean variables. • Composite data types, such as records, allow groups of fields to be defined and manipulated in PL/SQL blocks. • Reference data types hold values, called pointers , that designate other program items. Reference data types are not covered in this course. • LOB data types hold values, called locators , that specify the location of large objects (such as graphic images) that are stored out of line. LOB data types are discussed in detail later in this course. Non-PL/SQL variables include host language variables declared in precompiler programs, screen fields in Forms applications, and i SQL*Plus host variables. For more information on LOBs, see PL/SQL User’s Guide and Reference, “Fundamentals.”
Using i SQL*Plus Variables Within PL/SQL Blocks PL/SQL does not have input or output capability of its own. You must rely on the environment in which PL/SQL is executing to pass values into and out of a PL/SQL block. In the i SQL*Plus environment, i SQL*Plus substitution variables can be used to pass run time values into a PL/SQL block. You can reference substitution variables within a PL/SQL block with a preceding ampersand in the same manner as you reference i SQL*Plus substitution variables in a SQL statement. The text values are substituted into the PL/SQL block before the PL/SQL block is executed. Therefore you cannot substitute different values for the substitution variables by using a loop. Only one value will replace the substitution variable. i SQL*Plus host variables can be used to pass run-time values out of the PL/SQL block back to the i SQL*Plus environment. You can reference host variables in a PL/SQL block with a preceding colon. Bind variables are discussed in further detail later in this lesson.
Types of Variables The slide illustrates the following variable data types: • TRUE represents a Boolean value. • 25-JAN-01 represents a DATE. • The photograph represents a BLOB. • The text of a speech represents a LONG. • 256120.08 represents a NUMBER data type with precision and scale. • The movie represents a BFILE. • The city name, Atlanta, represents a VARCHAR2.
Declaring PL/SQL Variables You must declare all PL/SQL identifiers in the declaration section before referencing them in the PL/SQL block. You have the option to assign an initial value to a variable. You do not need to assign a value to a variable in order to declare it. If you refer to other variables in a declaration, you must be sure to declare them separately in a previous statement. In the syntax: identifier is the name of the variable. CONSTANT constrains the variable so that its value cannot change; constants must be initialized. data type is a scalar, composite, reference, or LOB data type. (This course covers only scalar, composite, and LOB data types.) NOT NULL constrains the variable so that it must contain a value. (NOT NULL variables must be initialized.) expr is any PL/SQL expression that can be a literal expression, another variable, or an expression involving operators and functions.
Guidelines for Declaring PL/SQL Variables Here are some guidelines to follow while declaring PL/SQL variables: • Name the identifier according to the same rules used for SQL objects. • You can use naming conventions—for example, v_name to represent a variable and c_name to represent a constant variable. • If you use the NOT NULL constraint, you must assign a value. • Declaring only one identifier per line makes code easier to read and maintain. • In constant declarations, the keyword CONSTANT must precede the type specifier. The following declaration names a constant of NUMBER subtype REAL and assigns the value of 50000 to the constant. A constant must be initialized in its declaration; otherwise, you get a compilation error when the declaration is elaborated (compiled). v_sal CONSTANT REAL := 50000.00; • Initialize the variable to an expression with the assignment operator (:=) or, equivalently, with the DEFAULT reserved word. If you do not assign an initial value, the new variable contains NULL by default until you assign a value later. To assign or reassign a value to a variable, you write a PL/SQL assignment statement. You must explicitly name the variable to receive the new value to the left of the assignment operator (:=). It is good programming practice to initialize all variables.
Naming Rules Two objects can have the same name, provided that they are defined in different blocks. Where they coexist, only the object declared in the current block can be used. You should not choose the same name (identifier) for a variable as the name of table columns used in the block. If PL/SQL variables occur in SQL statements and have the same name as a column, the Oracle server assumes that it is the column that is being referenced. Although the example code in the slide works, code that is written using the same name for a database table and variable name is not easy to read or maintain. Consider adopting a naming convention for various objects that are declared in the DECLARE section of the PL/SQL block. Using v_ as a prefix representing variable avoids naming conflicts with database objects. DECLARE v_hire_date date; BEGIN ... Note: The names of the variables must not be longer than 30 characters. The first character must be a letter; the remaining characters can be letters, numbers, or special symbols.
Variable Initialization and Keywords In the syntax: identifier is the name of the scalar variable. expr can be a variable, literal, or function call, but not a database column. The variable value assignment examples are defined as follows: • Set the identifier V_HIREDATE to a value of 01-JAN-2001. • Store the name “Maduro” in the V_ENAME identifier. Variables are initialized every time a block or subprogram is entered. By default, variables are initialized to NULL. Unless you explicitly initialize a variable, its value is undefined. Use the assignment operator (:=) for variables that have no typical value. v_hire_date := '15-SEP-1999' Note: This four-digit value for year, YYYY, assignment is possible only in Oracle8 i and later. Previous versions may require the use of the TO_DATE function. DEFAULT: You can use the DEFAULT keyword instead of the assignment operator to initialize variables. Use DEFAULT for variables that have a typical value. v_mgr NUMBER(6) DEFAULT 100; NOT NULL: Impose the NOT NULL constraint when the variable must contain a value. You cannot assign nulls to a variable defined as NOT NULL. The NOT NULL constraint must be followed by an initialization clause. v_city VARCHAR2(30) NOT NULL := 'Oxford‘ Note: String literals must be enclosed in single quotation marks. For example, 'Hello, world'. If there is a single quotation mark in the string, use a single quotation mark twice—for example, to insert a value FISHERMAN’S DRIVE, the string would be 'FISHERMAN''S DRIVE' . Another way to assign values to variables is to select or fetch database values into it. The following example computes a 10% bonus for the employee with the EMPLOYEE_ID 176 and assigns the computed value to the v_bonus variable. This is done using the INTO clause. DECLARE v_bonus NUMBER(8,2); BEGIN SELECT salary * 0.10 INTO v_bonus FROM employees WHERE employee_id = 176; END; / Then you can use the variable v_bonus in another computation or insert its value into a database table. Note: To assign a value into a variable from the database, use a SELECT or FETCH statement. The FETCH statement is covered later in this course.
Scalar Data Types Every constant, variable, and parameter has a data type (or type), which specifies a storage format, constraints, and valid range of values. PL/SQL provides a variety of predefined data types. For instance, you can choose from integer, floating point, character, Boolean, date, collection, reference, and LOB types. In addition, This chapter covers the basic types that are used frequently in PL/SQL programs. Later chapters cover the more specialized types. A scalar data type holds a single value and has no internal components. Scalar data types can be classified into four categories: number, character, date, and Boolean. Character and number data types have subtypes that associate a base type to a constraint. For example, INTEGER and POSITIVE are subtypes of the NUMBER base type. For more information and the complete list of scalar data types, refer to PL/SQL User’s Guide and Reference, “Fundamentals.”
Base Scalar Data Types Data Type Description CHAR [( maximum_length )] Base type for fixed-length character data up to 32,767 bytes. If you do not specify a maximum_length , the default length is set to 1. VARCHAR2 ( maximum_length ) Base type for variable-length character data up to 32,767 bytes. There is no default size for VARCHAR2 variables and constants. LONG Base type for variable-length character data up to 32,760 bytes. Use the LONG data type to store variable-length character strings. You can insert any LONG value into a LONG database column because the maximum width of a LONG column is 2**31 bytes. However, you cannot retrieve a value longer than 32760 bytes from a LONG column into a LONG variable. LONG RAW Base type for binary data and byte strings up to 32,760 bytes. LONG RAW data is not interpreted by PL/SQL. NUMBER [( precision, scale )] Number having precision p and scale s . The precision p can range from 1 to 38. The scale s can range from -84 to 127. BINARY_INTEGER Base type for integers between -2,147,483,647 and 2,147,483,647. PLS_INTEGER Base type for signed integers between -2,147,483,647 and 2,147,483,647. PLS_INTEGER values require less storage and are faster than NUMBER and BINARY_INTEGER values. BOOLEAN Base type that stores one of three possible values used for logical calculations: TRUE, FALSE, or NULL.
Data Type Description DATE Base type for dates and times. DATE values include the time of day in seconds since midnight. The range for dates is between 4712 B.C. and 9999 A.D. TIMESTAMP The TIMESTAMP data type, which extends the DATE data type, stores the year, month, day, hour, minute, and second. The syntax is: TIMESTAMP[(precision)] where the optional parameter precision specifies the number of digits in the fractional part of the seconds field. You cannot use a symbolic constant or variable to specify the precision; you must use an integer literal in the range 0 .. 9. The default is 6. TIMESTAMP WITH TIME ZONE The TIMESTAMP WITH TIME ZONE data type, which extends the TIMESTAMP data type, includes a time-zone displacement. The time-zone displacement is the difference (in hours and minutes) between local time and Coordinated Universal Time (UTC), formerly known as Greenwich Mean Time. The syntax is: TIMESTAMP[(precision)] WITH TIME ZONE where the optional parameter precision specifies the number of digits in the fractional part of the seconds field. You cannot use a symbolic constant or variable to specify the precision; you must use an integer literal in the range 0 .. 9. The default is 6. TIMESTAMP WITH LOCAL TIME ZONE The TIMESTAMP WITH LOCAL TIME ZONE data type, which extends the TIMESTAMP data type, includes a time-zone displacement. The timezone displacement is the difference (in hours and minutes) between local time and Coordinated Universal Time (UTC)—formerly Greenwich Mean Time. The syntax is: TIMESTAMP[(precision)] WITH LOCAL TIME ZONE where the optional parameter precision specifies the number of digits in the fractional part of the seconds field. You cannot use a symbolic constant or variable to specify the precision; you must use an integer literal in the range 0 .. 9. The default is 6. This data type differs from TIMESTAMP WITH TIME ZONE in that when you insert a value into a database column, the value is normalized to the database time zone, and the time-zone displacement is not stored in the column. When you retrieve the value, Oracle returns the value in your local session time zone. INTERVAL YEAR TO MONTH You use the INTERVAL YEAR TO MONTH data type to store and manipulate intervals of years and months. The syntax is: INTERVAL YEAR[(precision)] TO MONTH where years_precision specifies the number of digits in the years field. You cannot use a symbolic constant or variable to specify the precision; you must use an integer literal in the range 0 .. 4. The default is 2. INTERVAL DAY TO SECOND You use the INTERVAL DAY TO SECOND data type to store and manipulate intervals of days, hours, minutes, and seconds. The syntax is: INTERVAL DAY[(precision1)] TO SECOND[(precision2)] where precision1 and precision2 specify the number of digits in the days field and seconds field, respectively. In both cases, you cannot use a symbolic constant or variable to specify the precision; you must use an integer literal in the range 0 .. 9.The defaults are 2 and 6, respectively.
Declaring Scalar Variables The examples of variable declaration shown on the slide are defined as follows: • v_job: variable to store an employee job title • v_count: variable to count the iterations of a loop and initialized to 0 • v_total_sal: variable to accumulate the total salary for a department and initialized to 0 • v_orderdate: variable to store the ship date of an order and initialize to one week fromtoday • c_tax_rate: a constant variable for the tax rate, which never changes throughout the PL/SQL block • v_valid: flag to indicate whether a piece of data is valid or invalid and initialized to TRUE
The %TYPE Attribute When you declare PL/SQL variables to hold column values, you must ensure that the variable is of the correct data type and precision. If it is not, a PL/SQL error will occur during execution. Rather than hard coding the data type and precision of a variable, you can use the %TYPE attribute to declare a variable according to another previously declared variable or database column. The %TYPE attribute is most often used when the value stored in the variable will be derived from a table in the database. To use the attribute in place of the data type that is required in the variable declaration, prefix it with the database table and column name. If referring to a previously declared variable, prefix the variable name to the attribute. PL/SQL determines the data type and size of the variable when the block is compiled so that such variables are always compatible with the column that is used to populate it. This is a definite advantage for writing and maintaining code, because there is no need to be concerned with column data type changes made at the database level. You can also declare a variable according to another previously declared variable by prefixing the variable name to the attribute.
Declaring Variables with the %TYPE Attribute Declare variables to store the last name of an employee. The variable v_name is defined to be of the same data type as the LAST_NAME column in the EMPLOYEES table. %TYPE provides the data type of a database column: ... v_name employees.last_name%TYPE; ... Declare variables to store the balance of a bank account, as well as the minimum balance, which starts out as 10. The variable v_min_balance is defined to be of the same data type as the variable v_balance. %TYPE provides the data type of a variable: ... v_balance NUMBER(7,2); v_min_balance v_balance%TYPE := 10; ... A NOT NULL database column constraint does not apply to variables that are declared using %TYPE. Therefore, if you declare a variable using the %TYPE attribute that uses a database column defined as NOT NULL, you can assign the NULL value to the variable. …
Declaring Boolean Variables With PL/SQL you can compare variables in both SQL and procedural statements. These comparisons, called Boolean expressions, consist of simple or complex expressions separated by relational operators. In a SQL statement, you can use Boolean expressions to specify the rows in a table that are affected by the statement. In a procedural statement, Boolean expressions are the basis for conditional control. NULL stands for a missing, inapplicable, or unknown value. Examples v_sal1 := 50000; v_sal2 := 60000; The following expression yields TRUE: v_sal1 < v_sal2 Declare and initialize a Boolean variable: DECLARE v_flag BOOLEAN := FALSE; BEGIN v_flag := TRUE; END;
Composite Data Types A scalar type has no internal components. A composite type has internal components that can be manipulated individually. Composite data types (also known as collections) are of TABLE, RECORD, NESTED TABLE, and VARRAY types. Use the RECORD data type to treat related but dissimilar data as a logical unit. Use the TABLE data type to reference and manipulate collections of data as a whole object. Both RECORD and TABLE data types are covered in detail in a subsequent lesson. NESTED TABLE and VARRAY data types are covered in the Advanced PL/SQL course. For more information, see PL/SQL User’s Guide and Reference, “Collections and Records.” …
LOB Data Type Variables With the LOB (large object) data types you can store blocks of unstructured data (such as text, graphic images, video clips, and sound wave forms) up to 4 gigabytes in size. LOB data types allow efficient, random, piecewise access to the data and can be attributes of an object type. LOBs also support random access to data. • TheCLOB (character large object) data type is used to store large blocks of single-byte character data in the database in line (inside the row) or out of line (outside the row). • TheBLOB (binary large object) data type is used to store large binary objects in the database in line (inside the row) or out of line (outside the row). • TheBFILE (binary file) data type is used to store large binary objects in operating system files outside the database. • TheNCLOB (national language character large object) data type is used to store large blocks of single-byte or fixed-width multibyte NCHAR unicode data in the database, in line or out of line.
Bind Variables A bind variable is a variable that you declare in a host environment. Bind variables can be used to pass run-time values, either number or character, into or out of one or more PL/SQL programs. The PL/SQL programs use bind variables as they would use any other variable. You can reference variables declared in the host or calling environment in PL/SQL statements, unless the statement is in a procedure, function, or package. This includes host language variables declared in precompiler programs, screen fields in Oracle Developer Forms applications, and i SQL*Plus bind variables. Creating Bind Variables To declare a bind variable in the i SQL*Plus environment, use the command VARIABLE. For example, you declare a variable of type NUMBER and VARCHAR2 as follows: VARIABLE return_code NUMBER VARIABLE return_msg VARCHAR2(30) Both SQL and i SQL*Plus can reference the bind variable, and i SQL*Plus can display its value through the i SQL*Plus PRINT command. To display the current value of bind variables in the i SQL*Plus environment, use the PRINT command. However, PRINT cannot be used inside a PL/SQL block because it is an i SQL*Plus command. The following example illustrates a PRINT command: VARIABLE g_n NUMBER ... PRINT g_n You can reference host variables in PL/SQL programs. These variables should be preceded by a colon. VARIABLE RESULT NUMBER An example of using a host variable in a PL/SQL block: BEGIN SELECT (SALARY*12) + NVL(COMMISSION_PCT,0) INTO :RESULT FROM employees WHERE employee_id = 144; END; / PRINT RESULT
Printing Bind Variables In i SQL*Plus you can display the value of the bind variable using the PRINT command.
Referencing Non-PL/SQL Variables To reference host variables, you must prefix the references with a colon (:) to distinguish them from declared PL/SQL variables. Example This example computes the monthly salary, based upon the annual salary supplied by the user. This script contains both i SQL*Plus commands as well as a complete PL/SQL block. VARIABLE g_monthly_sal NUMBER DEFINE p_annual_sal = 50000 SET VERIFY OFF DECLARE v_sal NUMBER(9,2) := &p_annual_sal; BEGIN :g_monthly_sal := v_sal/12; END; / PRINT g_monthly_sal The DEFINE command specifies a user variable and assigns it a CHAR value. Even though you enter the number 50000, i SQL*Plus assigns a CHAR value to p_annual_sal consisting of the characters, 5,0,0,0 and 0.
DBMS_OUTPUT.PUT_LINE You have seen that you can declare a host variable, reference it in a PL/SQL block, and then display its contents in i SQL*Plus using the PRINT command. Another option for displaying information from a PL/SQL block is DBMS_OUTPUT.PUT_LINE. DBMS_OUTPUT is an Oracle-supplied package, and PUT_LINE is a procedure within that package. Within a PL/SQL block, reference DBMS_OUTPUT.PUT_LINE and, in parentheses, specify the string that you want to print to the screen. The package must first be enabled in your i SQL*Plus session. To do this, execute the i SQL*Plus SET SERVEROUTPUT ON command. The example on the slide computes the monthly salary and prints it to the screen, using DBMS_OUTPUT.PUT_LINE. The output is shown below:
Summary A PL/SQL block is a basic, unnamed unit of a PL/SQL program. It consists of a set of SQL or PL/SQL statements and it performs a single logical function. The declarative part is the first part of a PL/SQL block and is used for declaring objects such as variables, constants, cursors, and definitions of error situations called exceptions. The executable part is the mandatory part of a PL/SQL block, and contains SQL and PL/SQL statements for querying and manipulating data. The exception-handling part is embedded inside the executable part of a block and is placed at the end of the executable part. An anonymous PL/SQL block is the basic, unnamed unit of a PL/SQL program. Procedures and functions can be compiled separately and stored permanently in an Oracle database, ready to be executed.
Summary (continued) All PL/SQL data types are scalar, composite, reference, or LOB type. Scalar data types do not have any components within them, whereas composite data types have other data types within them. PL/SQL variables are declared and initialized in the declarative section. When a PL/SQL program is written and executed using i SQL*Plus, i SQL*Plus becomes the host environment for the PL/SQL program. The variables declared in i SQL*Plus are called host variables. Then the PL/SQL program is written and executed using, for example, Oracle Forms. Forms becomes a host environment, and variables declared in Oracle Forms are called host variables. Host variables are also called bind variables. To display information from a PL/SQL block use DBMS_OUTPUT.PUT_LINE. DBMS_OUTPUT is an Oracle-supplied package, and PUT_LINE is a procedure within that package. Within a PL/SQL block, reference DBMS_OUTPUT.PUT_LINE and, in parentheses, specify the string that you want to print to the screen.
Practice 1 Overview This practice reinforces the basics of PL/SQL covered in this lesson, including data types, definitions of identifiers, and validation of expressions. You put all these elements together to create a simple PL/SQL block. Paper-Based Questions Questions 1 and 2 are paper-based questions.
Practice 1 1. Initiate an i SQL*Plus session using the user ID and password provided by the instructor. 2. i SQL*Plus commands access the database. True/False 3. The following SELECT statement executes successfully: SELECT last_name, job_id, salary AS Sal FROM employees; True/False 4. The following SELECT statement executes successfully: SELECT * FROM job_grades; True/False 5. There are four coding errors in this statement. Can you identify them? SELECT employee_id, last_name sal x 12 ANNUAL SALARY FROM employees; 6. Show the structure of the DEPARTMENTS table. Select all data from the table.