Database Management Systems Using PL-SQL
Database Management Systems Using PL-SQL
Question: How can you create, reference, alter, and drop a sequence in SQL Server?
Use and Meaning:
Sequences are used to generate unique numeric values automatically, typically for primary
keys or IDs.
Script:
Explanation:
Outcome:
Conditional logic allows dynamic execution based on input parameters or conditions, enabling
decision-making in queries or stored procedures.
The IF...ELSE statement in SQL allows conditional execution of different sets of SQL
statements based on whether a specified condition evaluates to TRUE or FALSE. It is
commonly used to implement decision-making logic in stored procedures or scripts.
Script:
IF @Age >= 18
ELSE
IF @Marks >= 90
ELSE
Explanation:
3. LOOP Statements
Question: How can loops be used to repeatedly execute a set of statements in SQL?
Use and Meaning:
Loops automate repetitive tasks, such as processing or calculating values over multiple
iterations.
Loops in SQL are used to perform repetitive tasks, such as updating records, calculating
values, or processing rows in a dataset. They provide automation, reducing the need for
manual execution of repetitive operations.
Script:
-- Increment the ID
SET @ID = @ID + 1;
END;
Explanation:
Outcome:
Question: What are stored procedures, and how can you create and execute them in SQL?
Use and Meaning:
Stored procedures encapsulate reusable SQL code for modularity, efficiency, and reduced
redundancy.
A stored procedure is a precompiled collection of SQL statements and logic, stored in the
database. It can be reused, parameterized, and optimized for efficiency. Stored procedures
improve performance, enforce business logic, and simplify complex operations.
Script:
Explanation:
Outcome:
Question: How do you create a user-defined function and use it for calculations?
Use and Meaning:
Recursive functions are a special type of function that calls itself to solve problems that can
be broken down into simpler sub-problems, such as calculating factorials, Fibonacci
sequences, or hierarchical data traversal.
Script:
RETURN;
END;
Explanation:
Outcome:
● Learners understand how to create scalar and table-valued functions for computations
and series generation.
● Gain insights into using recursion for solving mathematical and hierarchical problems.
● Learn how functions simplify complex logic and enhance code reusability.
Question: How can you simulate an associative array using tables in SQL?
Use and Meaning:
Associative arrays, also known as key-value pairs or hash maps, store data as a collection of
unique keys and associated values. In SQL, associative arrays are typically implemented using
collections such as TABLE or ASSOCIATIVE ARRAY types in PL/SQL (Oracle) or SQL Server's
XML and JSON data types. They allow for quick lookups and efficient data storage when
key-value relationships are needed.
Script:
-- Step 2: Initialize the XML variable with key-value pairs (representing the associative array)
SET @AssociativeArray =
'<Items>
<Item>
<Key>1</Key>
<Value>Apple</Value>
</Item>
<Item>
<Key>2</Key>
<Value>Banana</Value>
</Item>
<Item>
<Key>3</Key>
<Value>Orange</Value>
</Item>
</Items>';
-- Step 3: Query the associative array using XML methods to extract data
SELECT
Item.value('(Key)[1]', 'INT') AS Key,
Item.value('(Value)[1]', 'NVARCHAR(50)') AS Value
FROM @AssociativeArray.nodes('/Items/Item') AS X(Item);
Explanation:
Outcome:
● Learners understand how to create and work with associative arrays using SQL Server’s
XML data type.
● Gain knowledge on querying, updating, and managing key-value pairs in SQL.
● Learn to use XML-based associative arrays to handle and store data in a flexible and
efficient way.
Question: How can you handle errors using TRY...CATCH in SQL Server?
Use and Meaning:
1. Error handling ensures program stability by catching and responding to runtime errors.
2. Error handling in SQL allows you to manage runtime errors gracefully without
terminating the execution of your SQL statements.
3. Exception propagation ensures that errors are passed up the call stack, enabling proper
error management in stored procedures, functions, and triggers.
4. This is especially useful in complex systems where multiple layers of logic are involved,
and errors need to be caught and handled at different levels.
Script:
AS
BEGIN
BEGIN TRY
END TRY
BEGIN CATCH
PRINT 'An error occurred: ' + ERROR_MESSAGE(); -- Print the error message
END CATCH;
END;
EXEC HandleErrorExample;
-- Step 3: Handling errors in a transaction
BEGIN TRY
BEGIN TRANSACTION;
VALUES (NULL, 'John', 'Doe'); -- This might cause an error due to NULL EmployeeID
COMMIT;
END TRY
BEGIN CATCH
ROLLBACK;
END CATCH;
Explanation:
Outcome:
● Learners can use TRY...CATCH for robust error handling in SQL, ensuring errors are
caught and managed properly.
● Gain knowledge about propagating errors back to the calling environment with THROW.
● Understand how to manage transactions in SQL, ensuring data integrity and
consistency even in case of errors.
Script:
Question: How can you create and manipulate multidimensional collections in SQL?
Use and Meaning:
Multidimensional collections allow you to store data in a format where multiple levels of
information are maintained within a single collection. These are commonly used to represent
tabular data, grids, or matrices. In SQL, multidimensional collections can be implemented
using arrays, tables, or nested collections within PL/SQL (Oracle) or SQL Server's XML/JSON
structures. These collections are useful when you need to model data with more than one
dimension, such as a list of lists (2D array) or more complex structures.
-- Step 2: Initialize the XML variable with multidimensional data (simulating a 2D array)
SET @MultiDimensionalCollection =
'<Matrix>
<Row>
<Column>1</Column>
<Column>2</Column>
<Column>3</Column>
</Row>
<Row>
<Column>4</Column>
<Column>5</Column>
<Column>6</Column>
</Row>
<Row>
<Column>7</Column>
<Column>8</Column>
<Column>9</Column>
</Row>
</Matrix>';
SELECT
SELECT
Explanation:
Outcome:
● Learners will understand how to use XML to create multidimensional collections in SQL
Server, simulating 2D arrays or matrices.
● Gain knowledge on how to query, filter, and update data in a structured,
multidimensional format.
● Learn how to leverage XML’s powerful querying and modification features for complex
data structures within SQL.
User-defined errors allow you to create specific exceptions for custom scenarios in SQL,
which may not be captured by predefined errors. This is useful when you need to handle
specific business logic violations, constraints, or conditions that are unique to your
application or database schema.
Using RAISEERROR in SQL Server (or RAISE in PL/SQL), you can raise custom errors with
detailed messages, error numbers, and state values, and then handle these errors within
TRY...CATCH blocks or exception handling routines.
-- Step 1: Create a stored procedure that checks for a specific condition and raises a
user-defined error
@EmployeeID INT,
@Salary DECIMAL(10, 2)
AS
BEGIN
IF @Salary < 0
BEGIN
RAISERROR('Salary cannot be negative.', 16, 1); -- Error severity 16: General errors
END
-- Step 3: Perform a task if the salary is valid (e.g., updating employee salary)
UPDATE Employees
END;
-- Step 4: Execute the stored procedure with valid and invalid input
BEGIN TRY
END TRY
BEGIN CATCH
-- Step 6: Catch the error and handle it (e.g., print the error message)
END CATCH;
Explanation:
Outcome:
● Learners will understand how to create and handle user-defined errors in SQL.
● Gain hands-on experience with using RAISEERROR in SQL Server to raise custom
exceptions for specific business logic errors.
● Learn how to handle these errors using TRY...CATCH and capture detailed
information about the errors that occur during execution.
UNIT 2
1. Cursors: Overview of Cursor, Types of Cursors, Invalid Cursor Exception
Question:
How can you create and use explicit cursors to fetch data, handle cursor exceptions, and
demonstrate invalid cursor handling?
Meaning:
A cursor is a pointer to a context area in SQL that allows you to process query result sets
row by row.
Uses:
Cursors are used when you need to fetch and process rows one at a time, often for complex
logic or row-specific processing.
Script:
FROM Employees;
OPEN employee_cursor;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'EmployeeID: ' + CAST(@EmployeeID AS NVARCHAR) + ', Name: ' + @FirstName + ' ' +
@LastName;
END;
CLOSE employee_cursor;
DEALLOCATE employee_cursor;
BEGIN TRY
END TRY
BEGIN CATCH
END CATCH;
Explanation:
● An explicit cursor is declared to fetch employee data from the Employees table.
● The cursor processes rows and prints the employee details.
● An error is generated by trying to fetch data after the cursor is deallocated,
demonstrating the invalid cursor exception.
Outcome:
The cursor fetches data correctly until deallocated. When an invalid cursor operation occurs,
the error handling catches and prints the exception message.
2. Static SQL: Description of Static SQL, Cursors Overview
Question:
How can you process query result sets using static SQL with cursors?
Meaning:
Static SQL refers to SQL queries that are predefined and executed without change each time
they run, as opposed to dynamic SQL which can change at runtime.
Uses:
Used when SQL queries are known in advance and do not need to be altered dynamically
during execution.
Script:
FROM Employees;
OPEN employee_cursor;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'EmployeeID: ' + CAST(@EmployeeID AS NVARCHAR) + ', FirstName: ' + @FirstName
+ ', Salary: ' + CAST(@Salary AS NVARCHAR);
END;
CLOSE employee_cursor;
DEALLOCATE employee_cursor;
Explanation:
● This script demonstrates the use of a STATIC cursor that fetches all employee
records.
● A WHILE loop is used to process and display each row retrieved by the cursor.
Outcome:
It prints each employee’s details. The cursor is static, which means the query doesn’t change
during execution, making the execution efficient.
Question:
How can you implement autonomous transactions and control commits in SQL?
Meaning:
Uses:
Used when a transaction must execute independently, for example, logging data while
performing a primary task.
Script:
-- Step 1: Create a stored procedure for autonomous transaction
AS
BEGIN
UPDATE Employees
END;
Explanation:
Outcome:
The salary update occurs without being affected by the surrounding transaction,
demonstrating the autonomous transaction.
4. Deadlocks Handling
Question:
Meaning:
A deadlock occurs when two transactions are waiting for each other to release resources,
causing the transactions to be stuck indefinitely.
Uses:
Handling deadlocks ensures that a system can recover gracefully from situations where
transactions are stuck.
Script:
BEGIN TRANSACTION;
BEGIN TRANSACTION;
-- Step 2: Deadlock will occur, SQL Server will automatically handle and resolve it by
terminating one of the transactions.
Explanation:
● The script simulates a deadlock scenario by having two transactions simultaneously
trying to update different rows that each other hold.
● SQL Server automatically resolves deadlocks by terminating one of the transactions.
Outcome:
A deadlock error is raised, and SQL Server resolves the conflict by terminating one of the
transactions.
Question:
How can you prevent SQL injection and implement native dynamic SQL?
Meaning:
Dynamic SQL refers to SQL code that is constructed at runtime, allowing flexibility in query
execution.
Uses:
Used to execute SQL commands that are determined dynamically, such as queries where
table names or column names are provided by the user.
Script:
Explanation:
Outcome:
The dynamic SQL executes successfully without causing SQL injection, as input is properly
sanitized.
Question:
Meaning:
A trigger is a database object that automatically executes or fires when certain events occur
in the database, like INSERT, UPDATE, or DELETE.
Uses:
Triggers are useful for enforcing data integrity, logging changes, or auditing database
modifications.
Script:
ON Employees
AFTER INSERT
AS
BEGIN
BEGIN
ROLLBACK TRANSACTION;
END;
END;
VALUES (6, 'Tom', 'Hanks', -500); -- This will cause an error due to the trigger
Explanation:
● This trigger ensures that any inserted employee record has a salary greater than 0,
enforcing business rules.
● If the condition fails, the transaction is rolled back with an error message.
Outcome:
If an invalid salary (<= 0) is inserted, the trigger raises an error and prevents the insertion,
maintaining data integrity
Question:
Meaning:
A delete trigger fires after a delete operation is executed on a table, often used for auditing or
maintaining integrity.
Uses:
Triggers are used to track deleted data or prevent data from being deleted improperly.
Script:
ON Employees
AFTER DELETE
AS
BEGIN
END;
Explanation:
Outcome:
The employee data is logged into the DeletedEmployeesLog table, providing an audit trail
for deleted records.
Question:
Meaning:
A package in PL/SQL is a collection of related procedures, functions, variables, and types that
are stored together in the database.
Uses:
Script:
END EmployeePackage;
BEGIN
UPDATE Employees
END UpdateSalary;
EmployeeName VARCHAR2(100);
BEGIN
FROM Employees
RETURN EmployeeName;
END GetEmployeeName;
END EmployeePackage;
Explanation:
● This script defines a Package with a procedure to update salary and a function to
retrieve employee names.
● The package body implements the logic for these operations.
Outcome:
The procedure updates the salary of an employee, and the function retrieves the full name.
The package encapsulates related functionality.
How can you create and work with nested tables in PL/SQL?
Meaning:
A nested table is a table data type that allows you to store multiple values in a single column.
Uses:
Nested tables are used when you need to store collections of items (e.g., a list of employees
within a department) within a row.
Script:
-- Step 1: Create a nested table type
CREATE OR REPLACE TYPE EmployeeTable AS TABLE OF VARCHAR2(50);
Explanation:
Outcome:
The nested table stores employee names and allows querying of the employee list for each
department.
Question:
How can you create an update trigger to prevent salary modifications to a specific value?
Meaning:
An update trigger is executed automatically when a record is updated in a table. It can be used to
enforce business rules.
Uses:
Used to prevent certain updates or enforce additional logic during record modification.
Script:
-- Step 1: Create an update trigger
CREATE TRIGGER trg_update_employee_salary
ON Employees
AFTER UPDATE
AS
BEGIN
IF UPDATE(Salary)
BEGIN
DECLARE @OldSalary DECIMAL(10, 2), @NewSalary DECIMAL(10, 2);
SELECT @OldSalary = Salary FROM deleted;
SELECT @NewSalary = Salary FROM inserted;
Explanation:
● This trigger prevents updates to the salary field if the new salary value is 100000.
● It raises an error and rolls back the transaction if the condition is met.
Outcome:
The update is blocked if the salary is set to 100000, ensuring that the business rule is maintained.