Вы находитесь на странице: 1из 47

PREFACE

Knowledge is precious but wisdom comes through experience. A famous method to explain but I try my best to give presentation and make short report on it. Philosopher once quoted these words to make people understand the importance of practical knowledge and how to represent this in front of the other people and the very important way is how to explain to them so that they could understand easily. Theory in any subject is important but that subject knowledge is important if should be understood by the other people in a very simple way by you. An Engineering student cannot be perfect engineer or professional without the practical, theoretical knowledge if he /she is not be able to represent that knowledge to you in a very simple way so that you can easily understood. I got the opportunity to make a presentation on the Oracle.

Introduction to Oracle
Oracle is most widely database used in the world. It runs virtually every kind of computer. It functions virtually identically on all the machines, so when we learn it on one, we can use it on any other. This fact makes knowledgeable oracle user and developers very much in demand, and makes oracle knowledge and skills very portable. Oracle can easily be used for simple operations such as entering multiple data and running standard reports. But an approach would ignore its great power; it would be like be buying a high performance racing car, and then pulling it around with a horse. Oracle is an Object-relational database. A relational database is an extremely simple way of thinking and managing the data used in business. It is nothing more than a collection of tables of data. We all encounter table every day: weather reports, stocks charts, sports scores. These all tables, with column headings and rows of information simply presented. Even so the relational approach can be sophisticated and powerful enough for even the most complex of business. An object relational database supports all of the features of a relational database while also supporting object-oriented concepts and features. Oracle has grown from its humble beginnings as one of a number of databases available in the 1970s to the market leader of today. In its early days, Oracle Corporation was known more as an aggressive sales and promotion organization than a technology supplier. Over the years, the Oracle database has grown in depth and quality, and its technical capabilities now are generally recognized as the most advanced. With each release, Oracle has added more power and features to its already solid base while improving the manageability.

Features of Oracle
To give some structure to the broad spectrum of the Oracle database, weve organized the features into the following sections:

Database application development features:

Database Programming:

All flavors of the Oracle database include different languages and interfaces that allow programmers to access and manipulate the data in the database. Database programming features usually interest two groups: developers building Oracle-based applications that will be sold commercially and IT organizations within companies that customdevelop applications unique to their businesses.

Database Extensibility:

The Internet and corporate intranets have created a growing demand for storage and manipulation of nontraditional data types within the database. There is a need for extensions to the standard functionality of a database for storing and manipulating image, audio, video, spatial, and time series information. These capabilities are enabled through extensions to standard SQL.

Database connection features:

Database Networking:

Database users connect to the database by establishing a network connection. You can also link database servers via network connections. Oracle provides a number of features to establish connections between users and the database and/or between Database servers.

Oracle Application Server:

The popularity of Internet and intranet applications has led to a change in deployment from client/server (with fat clients running a significant piece of the application) to three-tier architecture (with a browser supplying everything needed on a thin client). The Oracle Application Server provides a means of implementing the middle tier of a three-tier solution for web-based applications, component-based applications, and enterprise application integration.

Distributed database features:

Distributed Queries and Transactions:

Data within an organization is often spread among multiple databases for reasons of both capacity and organizational responsibility. Users may want to query this distributed data or update it as if it existed within a single database.

Heterogeneous Services:

Heterogeneous Services allow non-Oracle data and services to be accessed from an Oracle database through generic connectivity via ODBC and OLE-DB included with the database.

Data movement features:

Moving data from one Oracle database to another is often a requirement when using distributed databases, or when a user wants to implement multiple copies of the same database in multiple locations to reduce network traffic or increase data availability. You can export data and data dictionaries (metadata) from one database and import them into another.

Performance features:

Database Parallelization:

Databases tasks implemented in parallel speed up querying, tuning, and maintenance of the database. By breaking up a single task into smaller tasks and assigning each subtask to an independent process, you can dramatically improve the performance of certain types of database operation. Examples of query features implemented in parallel include: Table scans Nested loops Sort merge joins GROUP BYs NOT IN sub queries (anti-joins) User-defined functions Index scans Select distinct UNION and UNION ALL Hash joins ORDER BY and aggregation Bitmap star joins Partition-wise joins

Stored procedures (PL/SQL, Java, external routines)

Data Warehousing and Business Intelligence:

Oracle has also added some performance enhancements that specifically apply to data warehousing applications.

Database management features:

Oracle Enterprise Manager:

As part of every Database Server, Oracle provides the Oracle Enterprise Manager (EM), a database management tool framework with a graphical interface used to manage database users, instances, and features (such as replication) that can provide additional information about the Oracle environment. EM can also manage Oracles Application Server, Collaboration Suite, and E-Business Suite.

Backup and Recovery:

As every database administrator knows, backing up a database is a rather mundane but necessary task. An improper backup makes recovery difficult, if not impossible. Unfortunately, people often realize the extreme importance of this everyday task only when it is too late usually after losing business-critical data due to a failure of a related system.

Database Availability:

Database availability depends upon the reliability and management of the database, the underlying operating system, and the specific hardware components of the system. Oracle has improved availability by reducing backup and recovery times. It has done this through: Providing online and parallel backup and recovery. Improving the management of online data through range partitioning.
Oracle SQL

The history of SQL begins in an IBM laboratory in San Jose, California, where SQL was developed in the late 1970s. SQL stands for Structured Query Language, and the language itself is often referred to as "sequel." It is a standard and programming language.

SQL lets you access and manipulate databases. It was originally developed for IBM'sDB2 product. American National Standard Institute is primary organization for fostering of technology standard. Long established computer standard includes the American code for information interchange (ANSI). SQL is a nonprocedural language, in contrast to the procedural or third generation languages (3GLs) such as COBOL and C that had been created up to that time. Nonprocedural means what rather than how. For example, SQL describes what data to retrieve, delete, or insert, rather than how to perform the operation. Some common RDBMS that used SQL are ORACLE, CYBASE, and Microsoft SQL SERVER.

What Can SQL do?


SQL can execute queries against a database. SQL can retrieve data from a database. SQL can insert records in a database. SQL can update records in a database. SQL can delete records from a database. SQL can create new databases. SQL can create new tables in a database. SQL can create stored procedures in a database. SQL can create views in a database. SQL can set permissions on tables, procedures, and views.

SQL Statement
SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT Data retrieval Data manipulating language(DML)

Data definition language(DDL)

Transaction control

GRANT REVOKE Statement SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE

Data control language(DCL) Description Retrieves data from database Enter new rows, changes existing rows and removes unwanted rows from tables in the database, respectively. Set up changes and removes data structures from the tables.

Manages the changes made by DML statements. Changes to the data can be grouped together into logical transactions. Gives or remove access rights to both the Oracle database and the structure with in it.

SELECT Statement

Syntax:

SELECT [ALL|DISTINCT] columns/expr [AS new name] FROM table [WHERE conditions] [GROUP BY fields] [HAVING conditions] [ORDER BY column/integer [ASC|DESC]] SELECT Specifies the columns or fields to be included in the result set. DISTINCT FROM Identifies the tables or views from which the data will be retrieved. WHERE The predicate(s) that determine which rows will be retrieved. GROUP BY Use to group output by the field with duplicate values and apply group functions to the grouped data. HAVING Use to place a condition on results of group function calculations. ORDER BY Determines the sequence of the rows (Default order is

ascending).

Example: SELECT ename, age, add as Address, sal Salary FROM emp WHERE sal>10000 ORDER BY sal DESC;

Operators in SQL

Arithmatic operators:

Used for arithmetic operations. -, +, *, /.

Concatenation operator(||):

It combines columns or character string to other columns.

Comparison operators:

<,<= ,>, >=, (<>, !=, ^=). Other comparison operators: LIKE:

we use LIKE operator to perform wildcard search using % and _. % represents any sequence of zero or more characters. _ represents any single character.

IN:

Determine if a value is a member of a specific search set.

IS NULL:

Determine if a value is null.

BETWEENAND..:

Use to display rows based on a range of values.

Logical Operators:

AND, OR, NOT.

We can use NOT with various operators such as NOT IN, NOT BETWEEN, NOT LIKE etc.

Set Operators:

Set operators are used to combine results of two or more queries. UNION, UNION ALL, INTERSECT, MINUS.

Oracle SQL Functions

Number Functions:

Number functions accept numeric input and return numeric values. Example:

ABS (n), ROUND (n [, m]), TRUNC (n [, m])

Character Functions:

Character functions accept character input and return either character or numeric values. Example:

CONCAT (char1, char2), INITCAP (char), LOWER (char), LTRIM (char [, set]), LPAD (char, n [, char2])

Group Functions:

Default is to include all the candidate rows, but using DISTINCT causes the group functions to use only the distinct values of the argument expression. Example:

AVG ([DISTINCT | ALL] n), COUNT (* | [DISTINCT | ALL] expr), MAX ([DISTINCT | ALL] expr), MIN ([DISTINCT | ALL] expr), STDDEV ([DISTINCT | ALL] n), SUM ([DISTINCT | ALL] n), VARIANCE ([DISTINCT | ALL] n)

Date Functions and formats:

Date functions operate on values of the DATE data type.

All date functions return a value of DATE data type, except the MONTHS_BETWEEN function, which returns a number. Example:

TRUNC (d [,fmt]), SYSDATE, ROUND (d[,fmt]), NEXT_DAY (d,char), NEW_TIME (d, a, b), MONTHS_BETWEEN (d, e)

Conversion Functions:

Conversion functions convert a value from one data type to another. Generally, the form of the function names follows the convention data type TO data type, the first data type is the input data type; the last data type is the output data type. Example: The SYSDATE function returns the current date and time from Oracle. If you want to only manipulate the CURRENT DATE, and you are not selecting other columns from a table, you may issue a SELECT statement using the Oracle one row table: SELECT SYSDATE FROM DUAL;

Database Transaction

Transaction consists of statement that make up of a consistent change to the data. A database traction consists of one of the following:

DML statements which constitute one consistent change to the data. One DDL statement. One DCL statement.

A transaction begin when the 1st DML statement is encountered and ends when one of the following occur:

A COMMIT or ROLLBACK is issued. A DDL statement such as create is issued. A DCL statement is issued. The user exits iSQL*plus. A machine fails or the system crashes.

After transaction ends, the next executable statement automatically starts the next transaction. A DDL statement or a DCL statement is automatically committed and therefore implicitly ends the transaction.

Database Objects

There are several type of database objects:

Table:

It is a basic unit of storage composed of rows & columns.

View:

It logically represents subset of data from one or more tables.

Sequence:

It is used to generate primary key values.

Index:

Improves the performance of some queries.

Synonym:

It provides an alternative name for an object.

Table

It is a basic unit of storage composed of rows & columns. We dont need to specify size of the table at the time of creation. Table names & column names must begin with an alphabet. If a table does not belong to a user, the owner name must be prefix to the table.

Creating a Table

Syntax: CREATE TABLE [Schema].table_name ( column_name datatype [DEFAULT expr][column_constraint] . [table_constraint]

);

Example: CREATE TABLE emp (rollno number(5) CONSTRAINT emp_rollno_pk PRIMARY KEY, name varchar2(20) CONSTRAINT emp_name_nn NOT NULL, age number(2), CONSTRAINT emp_age_chk CHECK(age>20));

To create a table, a user must have CREATE TABLE privilage. DEFAULT option prevents NULL values from entering the column.

Constraint

Unique constraint:

Ensures that no two rows of a table can have duplicate values in a specific column or set of columns.

Primary key constraint:


Only one primary key can be created for a table. The primary key is column or set of columns that uniquely identifies each row in the table. The primary key constraint ensures that the columns cannot contain null values.

Foreign key constraint:

The FOREIGN key REFRENCE integrity constraint gesignates a column or a combination of columns as a foreign key and establish a relationship between primary key and unique key in the same table or different table. A foreign key value must match an existing value in the parent table or be null. ON DELETE CASCADE:

It deletes the dependent rows in the child table when a rpw in the parent table is deleted.

ON DELETE SET NULL:

It converts foreign key values to null when a row in parent table is removed.

Without these two options, the row in the parent table cant be deleted if it referenced in the child table.

Check constraint:

It defines a condition that each row must satisfy. The condition can use the same construct as query conditions with the following exception:

References to CURRVAL, NEXTVAL and ROWNUM pseudo columns. Calls to SYSDATE, UID, USER, functions.

Joining Tables

Having a common column in two tables implies a relationship between two tables, the nature of relationship is determined by which table uses the column as the primary key. Sometimes we have to select data from two or more tables to make our result complete, we have to perform a join. The common column appearing in the child table is referred to as foreign key.

Types of joins

Oracle property joins:


Equi join. Non-equi join. Outer join. Self join. Cartesian product.

SQL:1999 Compliant joins:


Natural join. Using clause. Full or left or right outer join. Arbitrary join condition using ON clause. Cross join.

View

A view is a logical table based on a table or another view. A view contains no data of its own but is like a window through which data from table can be viewed or changed. The view is stored as a select statement in the data dictionary.

Advantages of Views

View restricts access to a data because a view can display selected columns and rows from the table. View can be used to make a simple query to retrieve the result of complicated query. One view can be used to retrieve data from several tables.

Creating a View

Syntax:

CREATE [OR REPLACE][FORCE/NOFORCE] VIEW view_name [(alias (, alias).)] AS sub query [WITH CHECK OPTION [CONSTRAINT constraint_name]] [WITH READ ONLY [CONSTRAINT constraint_name]]; OR REPLACE Recreates the view if it exist. FORCE Creates the view regardless of whether or not the base table exists. NOFORCE Creates the view only if the base table exists. Alias Specify name for expression selected by the view query. WITH CHECK Specifies that only rows accessible to the view can OPTION be inserted or updated. WITH READ ONLY Ensures that no DML operation can be performed on this view.

Example:

CREATE VIEW v1 SELECT ename, job, deptno FROM emp Where deptno=20;

Removing a View

Syntax: DROP VIEW view_name;

Example: DROP VIEW v1;

Sequence

A sequence is a user created database object that can be shared by multiple user to generate a sequential series of unique integers. Normally a sequence is used to generate primary key values that must unique for each row. The sequence is generated & incremented by an internal Oracle Server routine. Two sequence methods

NextVal: provides the next value in a sequence. CurrVal: provides the current value in a sequence.

Creating a Sequence

Syntax:

CREATE SEQUENCE sequence_name [INCREMENT BY n] [START WITH n] [{MAXVALUE n/NOMAXVALUE}] [{MINVALUE n/NOMINVALUE}] [{CYCLE/NOCYCLE}] [{CACHE n/NOCACHE}] INCREMENT BY n Interval by which the sequence is incremented or decremented (default value is 1). START WITH n First no. to be generated (default is 1). MAXVALUE Max. value to be generated. NOMAXVALUE Specifies a max. value of 10^27 for an increasing sequence and -1 for a decreasing sequence. MINVALUE Min. value to be generated. NOMINVALUE Specifies a min. value of 1 for an increasing sequence and (10^26) for a decreasing sequence. CYCLE/NOCYCLE Specifies whether the sequence continues to

generate values after reaching its max. or min. values(default is NOCYCLE). CACHE/NOCACHE Specifies how many values the Oracle server preallocates and keep in memory(default is 20).

Example: CREATE SEQUENCE seq INCREMENT BY 10 START WITH 100 MAXVALUE 1000 CACHE 50;

Removing a Sequence

Syntax: DROP SEQUENCE sequence_name;

Example: DROP SEQUENCE seq;

Index

An Oracle server index is a schema object that can speed up of retrieval of rows by using a pointer. An index provides direct & fast access to rows in a table. Once index is created, no direct activity required by the user. If we dont have index of a column , then a full table scan occurs. When we drop a table, corresponding index is automatically drop.

Creating an Index

Syntax: CREATE INDEX index_name ON table_name(column,column..);

Example:

CREATE INDEX CustNameIdx ON CUSTOMER(Name);

Removing an Index

Syntax: DROP INDEX index_name;

Example: DROP INDEX CustNameIdx;

Synonym

To refer to a table owned by another user we need to prefix the table name with the name of the user who create it followed by a period.

Creating synonym eliminates the need to qualify the object name with the schema and provide us with an alternative name for a table, view, sequence, procedure, etc.

Creating an Synonym

Syntax: CREATE [PUBLIC] SYNONYM synonym_name FOR object;

Example: CREATE PUBLIC SYNONYM loc FOR smith. location;

Removing an Synonym

Syntax: DROP SYNONYM synonym_name;

Example: DROP SYNONYM loc;

Error handling

Prevents database locking. Ensures that errors are presented to the user in a sensible format. Makes code robust. Essential when using PL/SQL as formal programming language or interfacing with Oracle applications.

Grant & Revoke statement

Use the GRANT statement to grant:

System privileges to users and roles.

Both privileges and roles are either local, global, or external. Grant roles to users and roles. To grant the CREATE SESSION system privilege to the sample user hr, allowing hr to log on to Oracle Database, issue the following statement:

GRANT CREATE SESSION TO hr;

To grant the dw_manager role with the ADMIN OPTION to the sample user sh, issue the following statement:

GRANT dw_manager TO sh WITH ADMIN OPTION;

Use the REVOKE statement to:

Revoke system privileges from users and roles.

Revoke roles from users and roles. Revoke object privileges for a particular object from users and roles.

REVOKE UPDATE ON hr.employees FROM emp;

Enterprise Manager Console


The Oracle Enterprise Manager Console provides graphical facilities for managing an Oracle database. The utility can be used to manage:

Database structures such as tables and views. User accounts, passwords, roles, and privileges.

The Manager Console includes a SQL scratchpad for executing SQL statements.

Application Logic

Oracle database application can be processed using :


Programming language to invoke Oracle DBMS commands. Stored procedures. Start command to invoke database commands stored in .sql files. Triggers.

SQL*Plus

Oracle SQL*Plus or the Oracle Enterprise Manager Console may be used to manage an Oracle database. SQL*Plus is a text editor available in all Oracle. Except inside quotation marks of strings, Oracle commands are case-insensitive. The semicolon (;) terminates a SQL statement. The right-leaning slash (/) executes SQL statement stored in Oracle buffer. SQL*Plus can be used to:

Enter SQL statements. Submit SQL files created by text editors, e.g., notepad, to Oracle.

SQL*Plus Prompt

Oracle PL/SQL

Procedural Language/SQL (PL/SQL) is Oracle Corporations procedural language extension to SQL, the standard data access language for relational databases. PL/SQL offers modern software engineering features such as data encapsulation, exception handling, information hiding, object orientation, and brings state-of-the-art programming to the Oracle Server and toolset. PL/SQL incorporates many of the advanced features of programming languages that were designed during the 1970s and 1980s. It allows the data manipulation and query statements of SQL to be included

In block- structured and procedural units of code, making PL/SQL a powerful transaction processing language.

With PL/SQL, you can use SQL statements to finesse Oracle data, and PL/SQL control statements to process the data.

PL/SQL Environment

PL/SQL is not an Oracle product in its own right,it is a technology used by the Oracle server and by certain Oracle tools. Blocks of PL/SQL are passed to and processed by a PL/SQL engine, which may reside within the tool or within the Oracle server. The engine that is used depends on where the PL/SQL block is being invoked from. When you submit PL/SQL blocks from a Pro*C or a Pro*Cobol program, user-exit, iSQL*Plus, or Server Manager, the PL/SQL engine in the Oracle Server processes them. It separates the SQL statements and sends them individually to the SQL statements executor. A single transfer is required to send the block from the application to the Oracle Server, thus improving performance, especially in a client-server network. PL/SQL code can also be stored in the Oracle Server as subprograms that can be referenced by any number of applications connected to the database.

Benefits of PL/SQL

Integration:

PL/SQL plays a central role in both the Oracle server (through stored procedures, stored functions, database triggers, and packages) and Oracle development tools (through Oracle Developer component triggers). Oracle Forms Developer, Oracle Reports Developer, and Oracle Graphics Developer applications make use of shared libraries that hold code (procedures and functions) and can be accessed locally or remotely. SQL data types can also be used in PL/SQL. Combined with the direct access that SQL provides, these shared data types integrate PL/SQL with the Oracle server data dictionary. PL/SQL bridges the gap between convenient access to database technology and the need for procedural programming capabilities.

PL/SQL in Oracle Tools:

Many Oracle tools, including Oracle Developer, have their own PL/SQL engine, which is independent of the engine present in the Oracle Server. The engine filters out SQL statements and sends them individually to the SQL statement executor in the Oracle server. It processes the remaining procedural statements in the procedural statement executor, which is in the PL/SQL engine. The procedural statement executor processes data that is local to the application (that is, data already inside the client environment, rather than in the database). This reduces the work that is sent to the Oracle server and the number of memory cursors that are required.

Improved Performance:

PL/SQL can improve the performance of an application. The benefits differ depending on the execution environment. PL/SQL can be used to group SQL statements together within a single block and to send the entire block to the server in a single call, thereby reducing networking traffic.

Without PL/SQL, the SQL statements are sent to the Oracle server one at a time. Each SQL statement results in another call to the Oracle server and higher performance overhead. In a networked environment, the overhead can become significant. PL/SQL can also operate with Oracle Server application development tools such as Oracle Forms and Oracle Reports. By adding procedural processing power to these tools, PL/SQL enhances performance. You can take advantage of the procedural capabilities of PL/SQL, which are not available in SQL.

PL/SQL Block Structure:


Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely separate or nested one within another. The basic units (procedures, functions, and anonymous blocks) that make up a PL/SQL program are logical blocks, which can contain any number of nested sub blocks. Therefore, one block can represent a small part of another block, which in turn can be part of the whole unit of code.

Modularized Program Development:


Group logically related statements within blocks. Nest subblocks inside larger blocks to build powerful programs. Break down a complex problem into a set of manageable, well-defined, logical modules and implement the modules with blocks. Place reusable PL/SQL code in libraries to be shared between Oracle Forms and Oracle Reports applications or store it in an Oracle server to make it accessible to any application that can interact with an Oracle database.

Portability:

Because PL/SQL is native to the Oracle server, you can move programs to any host environment (operating system or platform) that supports the Oracle server and PL/SQL.

In other words, PL/SQL programs can run anywhere the Oracle server can run,you do not need to tailor them to each new environment. You can also move code between the Oracle server and your application. You can write portable program packages and create libraries that can be reused in different environments.

Identifiers:

In PL/SQL you can use identifiers to do the following:

Declare variables, cursors, constants, and exceptions and then use them in SQL and procedural statements. Declare variables belonging to scalar, reference, composite, and large object (LOB) data types. Declare variables dynamically based on the data structure of tables and columns in the database.

Procedural Language Control Structures:

Procedural Language Control Structures allow you to do the following:

Execute a sequence of statements conditionally. Execute a sequence of statements iteratively in a loop. Process individually the rows returned by a multiple-row query with an explicit cursor.

Errors:

The Error handling functionality in PL/SQL allows you to do the following:

Process Oracle server errors with exception-handling routines. Declare user-defined error conditions and process them with exception-handling routines.

PL/SQL Block Structure

The Declerative section contains all variables, constants, cursors, and userdefined exceptions that are referenced in the executable and declarative sections. Executable section contains SQL statements to manipulate data in the database and PL/SQL statements to manipulate data in the block. Exception handling section Specifies the actions to perform when errors and abnormal conditions arise in the executable section.

DBMS_OUTPUT.PUT_LINE

DBMS_OUTPUT is an oracle supplied package and PUT_LINE is a procedure within that package. This procedure is used to display output on the screen. We must set the SERVEROUTPUT variable to ON before we used the DBMS_OUTPUT.PUT_LINE.

Example: SET SERVEROUTPUT ON DEFINE p_annual_sal = 60000 DECLARE v_sal NUMBER(9,2) := &p_annual_sal; BEGIN v_sal := v_sal/12; DBMS_OUTPUT.PUT_LINE (The monthly salary is || TO_CHAR(v_sal)); END;

Handling Variables in PL/SQL


Declare and initialize variables in the declaration section. Assign new values to variables in the executable section. Pass values into PL/SQL blocks through parameters. View results through output variables.

Types of Variables

PL/SQL variables:

Scalar

hold a single value.

Composite

allow groups of fields to be defined and manipulated in PL/SQL blocks.

Reference

hold values, called pointers, that designate other program items.

LOB (large objects)

hold values, called locators, that specify the location of large objects (for example graphic images) that are stored out of line.

Non-PL/SQL variables:

Bind and host variables

host (or bind) variables can be used to pass run time values out of the PL/SQL block back to the iSQL*Plus environment.

Declaring PL/SQL Variables

Syntax:
identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];

Examples: DECLARE v_hiredate DATE; v_deptno NUMBER(2) NOT NULL := 10; v_location VARCHAR2(13) := Atlanta; c_comm CONSTANT NUMBER := 1400; v_mgr NUMBER(6) DEFAULT 100;

Identifier: is the name of the scalar variable. Expr: can be a variable, literal, or function call, but not a
database column. DEFAULT: You can use the DEFAULT keyword instead of the assignment operator to initialize variables. NOT NULL: Impose the NOT NULL constraint when the variable must contain a value.

SELECT Statements in PL/SQL


The INTO clause is required. Queries must return one and only one row. Syntax:

SELECT select_list INTO {variable_name[, variable_name]... | record_name} FROM table [WHERE condition];

Operators in PL/SQL Operator


** +, *, / +, -, || =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE, BETWEEN, IN NOT AND OR

Operation
Exponentiation Identity, negation Multiplication, division Addition, subtraction, concatenation Comparison

Logical negation Conjunction Inclusion

Controlling PL/SQL Flow of Execution

You can change the logical execution of statements using conditional IF statements and loop control structures.

Conditional IF statements:

Syntax:

IF condition THEN Statements; [ELSIF condition THEN Statements;] ELSE Statements;] END IF;

There are 3 forms of IF statement:

IF-THEN-END IF IF-THEN-ELSE-END IF IF-THEN-ELSIF-END IF

CASE Expressions:

Syntax:

CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2

... WHEN expressionN THEN resultN [ELSE resultN+1;] END;

Basic loop:

Syntax:

LOOP statement1; ... EXIT [WHEN condition]; END LOOP;

condition is a Boolean variable or expression (TRUE, FALSE, or NULL);

WHILE Loops:

Syntax:

WHILE condition LOOP statement1; statement2; ... END LOOP;


Condition is evaluated at the beginning of each iteration.

FOR Loops:

Syntax:

FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; ... END LOOP;

Do not declare the counter; it is declared implicitly.

Composite Data Types

PL/SQL Records:

A record is a group of related data items stored in fields, each with its own name and data type. Each record defined can have as many fields as necessary. Records can be assigned initial values and can be defined as NOT NULL. We can define RECORD types and declare user-defined records in the declarative part of any block, subprogram, or package. We can declare and reference nested records. One record can be the component of another record. Syntax:

TYPE type_name IS RECORD (field_declaration[, field_declaration]); identifier type_name;


Where field_declaration is:

field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr]

Example:

TYPE emp_record_type IS RECORD (last_name VARCHAR2(25), job_id VARCHAR2(10), salary NUMBER(8,2)); emp_record emp_record_type;

The %TYPE Attribute

Declare a variable according to:


A database column definition. Another previously declared variable.

Prefix %TYPE with:

The database table and column.

The previously declared variable name.

The ROW%TYPE Attribute


Declare a variable according to a collection of columns in a database table or view. Prefix %ROWTYPE with the database table. Fields in the record take their names and data types from the columns of the table or view.

INDEX BY Tables:

Are composed of two components:


Primary key of data type BINARY_INTEGER. Column of scalar or record data type.

Can increase in size dynamically because they are unconstrained. Syntax:

TYPE type_name IS TABLE OF {column_type|variable%TYPE |table.column%TYPE}[NOT NULL] | table.%ROWTYPE [INDEX BY BINARY_INTEGER]; Identifier type_name;

Example:

TYPE ename_table_type IS TABLE OF Employees.last_name%TYPE INDEX BY BINARY_INTEGER; ename_table ename_table_type;

Trapping Exceptions

Here we define the actions that should happen when an exception is thrown. Example Exceptions:

NO_DATA_FOUND TOO_MANY_ROWS ZERO_DIVIDE

When handling an exception, consider performing a rollback.

Example: DECLARE num_row number_table%ROWTYPE; BEGIN select * into num_row from number_table; dbms_output.put_line(1/num_row.num); EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line('No data!'); WHEN TOO_MANY_ROWS THEN dbms_output.put_line('Too many!'); WHEN OTHERS THEN dbms_output.put_line(Error); end;

Transaction Control Statements


Initiate a transaction with the first DML command to follow a COMMIT or ROLLBACK. Use COMMIT and ROLLBACK SQL statements to terminate a transaction explicitly.

PL/SQL Blocks

There are 3 types of blocks:

Anonyms:

It is a block code without anyname.

Procedure:

It is a named block that does some processing but does not return any result to the calling environment.

Function:

It is also a named block of code & it returns result to the calling environment.

Procedure

A Procedure is a type of subprogram that performs an action and does not return a value. It is a name of PL/SQL block that can accept parameter and can be removed. It can be compiled and stored in the database as a schema object. Promotes reusability and maintainability. Modes:

IN

procedure must be called with a value for the parameter. Value cannot be changed.

OUT

Procedure must be called with a variable for the parameter. Changes to the parameter are seen by the user (i.e., call by reference).

IN OUT

Value can be sent, and changes to the parameter are seen by the user.

Default Mode is: IN.

Creating Procedures

Syntax: CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] IS|AS PL/SQL Block;

Example: Create or replace query_emp(p_id IN emp.empno%TYPE, p_name OUT emp.ename%TYPE) BEGIN SELECT ename, sal, deptno INTO p_name, p_sal, p_deptno from emp Where empno=p_id; END; ISQL*PLUS-Execute query_emp(1046,:name); PRINT NAME

Removing Procedure

Drop a procedure stored in the database. Syntax:

DROP PROCEDURE procedure_name;

Example:

DROP PROCEDURE query_emp;

Function

A function is a named PL/SQL block that can return a value. A function can be stored in the database as a schema object for repeated execution. A function is called as part of an expression.

Creating Function

Syntax: CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] RETURN datatype IS|AS PL/SQL Block;

Example: CREATE [OR REPLACE] FUNCTION squareFunc ( num IN number ) RETURN number IS BEGIN return num*num; END;

Using the function BEGIN dbms_output.put_line(squareFunc(3.5)); END;

Removing Function

Drop a function stored in the database. Syntax:

DROP FUNCTION function_name;

Example:

DROP FUNCTION squarefunc;

Database Trigger

A database trigger is a procedure that is run automatically when an event occurs. The event could be an insert, a deletion, or even a selection of data from a table.
For example, we might define a trigger that is executed when someone attempts to insert a row into a table, and the trigger checks that the inserted data is valid.

Types of Triggers

On the basis of timing when the trigger is executed

Before and After trigger:

Triggers can be executed before and after insert, update and delete.

Instead of trigger:

Used to tell ORACLE what to do instead of performing the action that invoked the trigger.

On the basis of level at which the trigger is executed

Row level trigger:

The trigger body executes once for each row affected by the triggering event.

Statemant level trigger:

The trigger body executes once for the triggering event. This is the default.

Schema trigger:

We can triggers on schema level operations such as ceate, alter, drop etc. These triggers provides to capabilities preventing DDL operation and providing additional security, monitoring when DDL operation occurs.

Database trigger:

We can create trigger to be fired on database events such as logon, logout, shutdown, errors etc.

Creating DML Triggers

Syntax:

CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table/view name [REFERENCING OLD AS old | NEW AS new] [FOR EACH ROW]

[WHEN (condition)]
trigger_body

Trigger_name
timing

Event Table name REFERENCING FOR EACH ROW WHEN trigger body

Is the name of the trigger Indicates the time when the trigger fires in relationto the triggering event: BEFORE,AFTER,INSTEAD OF Identifies data manipulation operation that causes the trigger to fire: INSERT, UPDATE, DELETE Indicates the table associated with the trigger Specifies correlation names for the old and new values of the current row (The defaults are OLD and NEW) Designates that the trigger is a row trigger Specifies the trigger restriction Is the trigger body that defines the action performed by the trigger, beginning with either DECLARE or BEGIN, ending with END, or a call to a procedure

Example: CREATE OR REPLACE TRIGGER secure_emp BEFORE INSERT ON employees BEGIN

IF (TO_CHAR (SYSDATE,DY) IN (SAT,SUN)) OR (TO_CHAR (SYSDATE,HH24: MI) NOT BETWEEN 08:00 AND 18:00) THEN RAISE_APPLICATION_ERROR (-20500,you may Insert into EMPLOYEES table only During business hours.); END IF; END;

Disabling and Dropping Triggers

To remove a trigger:

DROP TRIGGER trigger_name;

To disable/enable a trigger:

ALTER TRIGGER trigger_name [ENABLE | DISABLE];

Example:

DROP TRIGGER secure_emp; ALTER TRIGGER secure_emp DISABLE;

Note:

All triggers on a table are dropped when the table is dropped.

Cursor

A cursor can be visualized as an array that is used to store one or more rows return by query. Whenever you issue a SQL statement, the Oracle server opens an area of memory in which the command is parsed and executed. This area is called a cursor. There are two types of cursors:

Implicit cursors:

Are declared by PL/SQL engine implicitly for all DML and PL/SQL select statement, including query that return only one row.

Explicit cursors:

For query that return more than one row, explicit cursor are declared and named by the programmer.

Step to use a cursor:

Declare the cursor

Syntax:

CURSOR cursor_name is SELECT statement;

Open the cursor

Syntax:

OPEN cursor_name;

Retrieve data using the fetch statement

Synatx:

FETCH cursor_name INTO variable;

Close the cursor

Synatx:

CLOSE cursor_name;

Example:

v_empid number; Cursor cur_sample is Select empid from employee where grade > 4; Begin open cur_sample; loop fetch cur_sample into v_empid; exit when cur_sample%notfound; update employee set salary = salary + 500

where empid = v_empid; end loop; End;

SQL Cursor Attributes


There are four attributes that can be apply to cursor

%rowcount:

Returns the number of rows fetch by the cursor so far (an integer value).

%found:

Boolean attribute that evaluates to TRUE if the previous fetch returns a row else FALSE.

%notfound:

Boolean attribute that evaluates to TRUE if previous fetch did not returns a row else FALSE.

%isopen:

Boolean attribute that evaluates to TRUE if cursor is open,FALSE otherwise.

Cursor FOR Loops

Syntax: FOR record_name IN cursor_name LOOP statement 1; statement 2; ................ END LOOP;

The cursor FOR loop is a shortcut to process cursors. Implicitly opens, fetches, and closes cursor. The record is implicitly declared. Example: DECLARE CURSOR emp_cursor IS SELECT ename, deptno FROM emp; BEGIN FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN ... END LOOP; -- implicit close occurs END;

Package

Packages bundle related PL/SQL types, items, and subprograms into one container. A package usually has a specification and a body, stored separately in the database. The package specification declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The body fully defines cursors and subprograms, and so implements the specification. When you call a packaged PL/SQL construct for the first time, the whole package is loaded into memory. Description Placement within the

Scope of the

Construct Public

Private

Package Can be referenced from any Declared within the package Oracle server environment specification and may be defined within the package body Can be referenced only by Declared and defined within other constructs which are the package body part of the same package

Creating the Package Specification

Syntax:

CREATE [OR REPLACE] PACKAGE package_name IS|AS public type and item declarations subprogram specifications END package_name;

Example:

CREATE OR REPLACE PACKAGE comm_package IS g_comm NUMBER := 0.10; --initialized to 0.10 PROCEDURE reset_comm (p_comm IN NUMBER); END comm_package;

Creating the Package Body

Syntax:

CREATE [OR REPLACE] PACKAGE BODY package_name IS|AS private type and item declarations subprogram bodies END package_name;

Example:

CREATE OR REPLACE PACKAGE BODY comm_package IS FUNCTION validate_comm (p_comm IN NUMBER) RETURN BOOLEAN IS v_max_comm NUMBER;

BEGIN SELECT MAX(commission_pct) INTO v_max_comm FROM employees; IF p_comm > v_max_comm THEN RETURN(FALSE); ELSE RETURN(TRUE); END IF; END validate_comm;

Removing Packages

To remove the package specification and the body, use the following syntax:

DROP PACKAGE package_name;

To remove the package body, use the following syntax :

DROP PACKAGE BODY package_name;

I took assistance and consulted from the underneath named sources of information:

Introduction_To_Oracle9i_SQL_Student_Guide. Introduction_To_Oracle9i_PL-SQL_Student_Guide. Official website of IBM.

ww.oracle.com

Encyclopedia website.

www.wikipedia.com

Вам также может понравиться