[go: up one dir, main page]

0% found this document useful (0 votes)
8 views10 pages

PLSQL

SQL worksheet

Uploaded by

mashhood
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views10 pages

PLSQL

SQL worksheet

Uploaded by

mashhood
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

PL/SQL Environment

PL/SQL (Procedural Language/Structured Query Language) is a


programming language that is used for database development and
management in the Oracle Database Management System (DBMS). The
PL/SQL environment refers to the environment in which PL/SQL code is
written, compiled, and executed. It consists of several components and
elements:

1. PL/SQL Code: This is the core of the PL/SQL environment. PL/SQL


code consists of blocks of code that can be used to perform various
tasks, such as querying and manipulating data in the database,
defining functions and procedures, and handling exceptions.
2. PL/SQL Developer Tools: These are the tools that developers use
to write, test, and manage PL/SQL code. These tools can include
Integrated Development Environments (IDEs) like Oracle SQL
Developer or third-party tools that provide features for code editing,
debugging, and version control.
3. SQL Engine: PL/SQL code can include SQL statements that interact
with the database. The SQL engine processes these statements, and
the PL/SQL environment allows for the seamless integration of SQL
and PL/SQL code.
4. PL/SQL Compiler: PL/SQL code must be compiled before it can be
executed. The PL/SQL compiler checks the code for syntax errors
and generates an executable form of the code, which is then stored
in the database for execution.
5. Database Server: The PL/SQL environment runs within the Oracle
Database server. It allows for direct interaction with the database,
including data retrieval, modification, and management.
6. PL/SQL Runtime: Once the PL/SQL code is compiled, it can be
executed in the PL/SQL runtime environment. This is where the code
is actually run and performs the operations specified in the code.
7. Data Dictionary: PL/SQL code can access the data dictionary,
which is a set of database tables and views that store information
about the structure of the database, such as tables, columns,
constraints, and privileges. Developers can query the data
dictionary to retrieve metadata about the database objects.
8. Error Handling and Exception Handling: PL/SQL provides robust
error and exception handling mechanisms, allowing developers to
define how to handle errors and exceptions that may occur during
the execution of PL/SQL code.
9. Security and Permissions: The PL/SQL environment operates
within the security framework of the Oracle Database. It adheres to
database security rules, permissions, and roles, ensuring that only
authorized users can execute PL/SQL code and access data.
10. Transaction Control: PL/SQL supports transaction
management, allowing developers to define and control
transactions, including committing and rolling back changes made
to the database within PL/SQL code.

Benefits of PL/SQL

Exception handling

Integration of procedural constructs with SQL

Client-Server Model
SQL results in many network trips, one for each SQL statement • PL/SQL permits several SQL
statements to be bundled into a single block • Results in fewer calls to database • Less network
traffic • faster response time
PL/SQL Block Structure
In PL/SQL, a program is organized into blocks, and these blocks are the basic building units of PL/SQL
programs. A PL/SQL block consists of the following sections:

1. **Declarative Section (Optional)**: This section is where you declare variables, constants, and
cursors that will be used within the block. It is optional, so you can choose to skip it if your code
doesn't require any variable declarations.

2. **Executable Section (Required)**: This is the main part of the block where you write the actual
PL/SQL code to perform various operations like data manipulation, calculations, and control flow.

3. **Exception Handling (Optional)**: In this section, you handle exceptions or errors that might
occur during the execution of the block. It allows you to gracefully manage and report errors.

Here's an example of a simple PL/SQL block:

```plsql

DECLARE

-- Declarative Section

my_variable NUMBER;

my_constant CONSTANT NUMBER := 10;

BEGIN

-- Executable Section

my_variable := my_constant * 5;

DBMS_OUTPUT.PUT_LINE('Result: ' || my_variable);


-- Exception Handling

EXCEPTION

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);

END;

```

Let's break down this example:

1. **Declarative Section**: In the `DECLARE` section, we declare a variable named `my_variable` of


type `NUMBER` and a constant named `my_constant` with a value of 10. This section is optional and
can be omitted if you have no declarations.

2. **Executable Section**: In the `BEGIN` and `END` block, we have the main PL/SQL code. In this
case, we calculate the value of `my_variable` by multiplying `my_constant` by 5 and then use
`DBMS_OUTPUT.PUT_LINE` to display the result.

3. **Exception Handling**: We have an exception handler that catches any exceptions raised during
the execution of the block. In this example, we catch any exception of type `OTHERS`, which is a
catch-all for any unhandled exceptions. We then use `DBMS_OUTPUT.PUT_LINE` to display an error
message containing information about the exception.

You can execute this PL/SQL block within an appropriate environment, like Oracle SQL*Plus or Oracle
SQL Developer, to see the result. In this example, it calculates the result and handles errors if any
occur. PL/SQL allows you to build more complex programs by combining and nesting these basic
blocks.
TYPES OF BLOCKS:

In PL/SQL, you can define three types of blocks: anonymous blocks, procedures, and functions. I'll
explain each of these and provide an example for each:

1. **Anonymous Block**:

- An anonymous block is a set of PL/SQL statements that are not named and can be executed
directly.

- Anonymous blocks are typically used for ad-hoc operations or for running PL/SQL code outside of
stored procedures or functions.

Example of an anonymous block:

```plsql

BEGIN

-- PL/SQL statements go here

DBMS_OUTPUT.PUT_LINE('Hello, World!');

-- More statements

END;

```

In this example, we have an anonymous block that uses `BEGIN` and `END;` to enclose a set of
PL/SQL statements. It uses `DBMS_OUTPUT.PUT_LINE` to display "Hello, World!" in the console. The
`/` at the end is used to execute the anonymous block in Oracle SQL*Plus.

2. **Procedure**:

- A procedure is a named PL/SQL block that performs a specific task. It can have input and output
parameters but does not return a value.

- Procedures are often used for encapsulating reusable code that can be called multiple times.
Example of a procedure:

```plsql

CREATE OR REPLACE PROCEDURE greet(name IN VARCHAR2) IS

BEGIN

DBMS_OUTPUT.PUT_LINE('Hello, ' || name);

END greet;

```

In this example, we create a procedure named `greet` that takes a single input parameter, `name`.
When the procedure is called, it uses `DBMS_OUTPUT.PUT_LINE` to greet the specified name.

3. **Function**:

- A function is a named PL/SQL block that performs a specific task and returns a single value.
Functions can have input parameters and are used to compute and return a result.

- Functions are often used in SQL queries or as part of expressions to retrieve calculated values.

Example of a function:

```plsql

CREATE OR REPLACE FUNCTION calculate_area(length IN NUMBER, width IN NUMBER) RETURN


NUMBER IS

area NUMBER;

BEGIN

area := length * width;

RETURN area;

END calculate_area;

```
In this example, we create a function named `calculate_area` that takes two input parameters,
`length` and `width`. It calculates the area by multiplying the two parameters and then uses the
`RETURN` statement to return the calculated area as a result.

The `%TYPE` attribute is a feature in PL/SQL that allows you to declare a variable or
parameter with the same data type as an existing database column or another PL/SQL variable. It
provides a way to ensure that a new variable's data type matches an existing data source without
explicitly specifying the data type. This can help improve code maintainability and reduce the risk of
data type-related errors.

The `%TYPE` attribute is commonly used in variable declarations, procedure parameters, and
function return types. Here's how you can use it:

1. **Variable Declaration**:

You can declare a variable using the `%TYPE` attribute to ensure it has the same data type as a
specific database column. For example:

```plsql

DECLARE

employee_id employees.employee_id%TYPE;
BEGIN

-- Code using employee_id

END;

```

In this example, the `employee_id` variable is declared with the same data type as the
`employee_id` column in the `employees` table.

2. **Procedure or Function Parameters**:

You can use the `%TYPE` attribute to declare parameters of procedures or functions. This ensures
that the parameters have the same data type as specific database columns. For example:

```plsql

CREATE OR REPLACE PROCEDURE update_employee_salary (

p_employee_id employees.employee_id%TYPE,

p_new_salary employees.salary%TYPE

) IS

BEGIN

-- Procedure code

END update_employee_salary;

```

In this example, the `p_employee_id` and `p_new_salary` parameters have data types that match
the `employee_id` and `salary` columns in the `employees` table.

3. **Function Return Type**:

You can use the `%TYPE` attribute to specify the return data type of a function based on a database
column. For example:

```plsql

CREATE OR REPLACE FUNCTION get_employee_name(

p_employee_id employees.employee_id%TYPE
) RETURN employees.first_name%TYPE IS

v_first_name employees.first_name%TYPE;

BEGIN

-- Function code to retrieve and return the first name

END get_employee_name;

```

In this case, the return type of the `get_employee_name` function is based on the data type of the
`first_name` column in the `employees` table.

The `%TYPE` attribute is a useful feature for maintaining data consistency in your PL/SQL code and
ensuring that variables and parameters align with the data types of database columns. It can also
make your code more robust and reduce the chances of type-related errors.
Bind variable:

You might also like