Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Module-10.-Lesson-Proper

The document provides an overview of stored procedures and triggers in database systems, detailing their definitions, purposes, advantages, and disadvantages. Stored procedures encapsulate SQL statements for improved performance, security, and consistency, while triggers automatically execute SQL statements in response to specific events to maintain data integrity. Both concepts have their complexities and potential drawbacks, such as debugging difficulties and performance overhead.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module-10.-Lesson-Proper

The document provides an overview of stored procedures and triggers in database systems, detailing their definitions, purposes, advantages, and disadvantages. Stored procedures encapsulate SQL statements for improved performance, security, and consistency, while triggers automatically execute SQL statements in response to specific events to maintain data integrity. Both concepts have their complexities and potential drawbacks, such as debugging difficulties and performance overhead.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Page 1 of 12

Advance Database System


Stored Procedure and Triggers

I. LESSON PROPER

What are Stored Procedures?


A stored procedure is a precompiled collection of one or more SQL statements stored in the database.
It can accept parameters, execute business logic, and return results, making it a powerful tool for
encapsulating complex operations.

Purpose

Stored procedures are used to:

• Encapsulate Logic: Group SQL statements and business rules into a single callable unit.
• Improve Performance: Reduce network traffic and increase execution speed by minimizing the
number of calls made to the database.
• Enhance Security: Control access to data and operations, allowing users to execute procedures
without direct access to the underlying tables.
• Ensure Consistency: Standardize database operations and enforce business rules consistently.

Advantages of Stored Procedures


1. Performance Improvement
• Precompiled execution reduces parsing time.
2. Code Reusability
• Allows developers to reuse code, leading to less duplication.
3. Enhanced Security
• Users can be granted permissions to execute procedures without direct access to the underlying
tables.
4. Reduced Network Traffic
• Batch processing reduces the number of calls between the application and the database.
5. Easier Maintenance
• Changes in business logic can be managed within the procedure without altering application code.

Disadvantages of Stored Procedures


1. Complexity
• Can lead to complicated code that may be hard to understand and maintain.
2. Vendor Lock-in
• Different databases have different stored procedure languages, making it challenging to migrate
across platforms.
3. Debugging Difficulties
• Debugging stored procedures can be more complex than debugging application code.
4. Performance Overhead
• Inefficient procedures can lead to performance issues if not properly optimized.
Page 2 of 12
Advance Database System
Stored Procedure and Triggers

5. Dependency Issues
• Changes in database schema can affect stored procedures, leading to potential failures.
Syntax Overview

Here's a basic structure for creating a stored procedure:

Example

Let's look at a simple example that inserts a new record into a "Customers" table:

Execution

To execute a stored procedure, you can use the following syntax:

For the GetCustomerCount procedure with an output parameter, the execution would look like this (syntax
may vary slightly based on the RDBMS):
Page 3 of 12
Advance Database System
Stored Procedure and Triggers

Error Handling

Error handling in stored procedures is important to ensure that exceptions are managed gracefully.
Many RDBMSs support constructs for error handling.

Basic Error Handling Example (Using MySQL):

You can use DECLARE ... HANDLER to define how to handle errors:

In this example:

• If an error occurs during the INSERT, the procedure will catch it and return a message instead of
failing outright.

Using Try-Catch Blocks (e.g., in SQL Server):

In some RDBMS, you can use try-catch blocks for error handling.
Page 4 of 12
Advance Database System
Stored Procedure and Triggers

Basic Syntax for Stored Procedures


1. Creating a Stored Procedure

To create a stored procedure, use the CREATE PROCEDURE statement. Here’s the basic syntax:

Example: Let’s create a simple stored procedure that adds a new customer:

Using Parameters

Stored procedures can accept various types of parameters:

• IN: Input parameters that provide values to the procedure.


• OUT: Output parameters that return values from the procedure.
• INOUT: Parameters that can both receive and return values.

Example with Output Parameter:


Page 5 of 12
Advance Database System
Stored Procedure and Triggers

Control Flow

Stored procedures can include control flow statements, such as IF, CASE, and loops (WHILE, REPEAT,
FOR). This allows for more complex logic.

Example with Control Flow:


Page 6 of 12
Advance Database System
Stored Procedure and Triggers

2. Altering a Stored Procedure

To modify an existing stored procedure, use the ALTER PROCEDURE statement. Note that the
exact syntax can depend on the RDBMS you are using. Here’s a general approach:

Example:

3. Dropping a Stored Procedure

To remove a stored procedure from the database, use the DROP PROCEDURE statement:

Example:
Page 7 of 12
Advance Database System
Stored Procedure and Triggers

Introduction to Triggers
A trigger is a set of SQL statements automatically executed (or fired) in response to specific events
on a particular table or view in a database. Triggers help maintain data integrity and enforce business rules.

Types of Triggers

1. BEFORE Trigger

A BEFORE Trigger is executed before an insert, update, or delete operation on a table. It is useful
for validating or modifying the data before it is committed to the database.

➢ BEFORE INSERT Trigger

Example: Validate Age Before Inserting a Customer

➢ BEFORE UPDATE Trigger

Example: Prevent Updating to an Inactive Status


Page 8 of 12
Advance Database System
Stored Procedure and Triggers

3. BEFORE DELETE Trigger

Example: Prevent Deletion of VIP Customers

2. AFTER Trigger

An AFTER Trigger is executed after an insert, update, or delete operation. This is useful for actions
that should happen after the main operation, such as logging or cascading changes.

➢ AFTER INSERT Trigger

Example: Log New Customer Addition


Page 9 of 12
Advance Database System
Stored Procedure and Triggers

➢ AFTER UPDATE Trigger

Example: Log Changes to Customer Information

➢ AFTER DELETE Trigger

Example: Log Customer Deletion

3. INSTEAD OF Trigger

An INSTEAD OF Trigger replaces the standard action for an insert, update, or delete operation. This is
commonly used with views, allowing for customized handling of actions.
Page 10 of 12
Advance Database System
Stored Procedure and Triggers

Use Cases for Triggers


1. Auditing: Triggers can be used to automatically log changes made to important tables, providing a
history of modifications.

Example: Log every change to a "Users" table.

2. Data Validation: Triggers can enforce data integrity by validating data before it’s inserted or updated in
the database.

Example: Prevent inserting a product with a negative price.

3. Cascading Actions: Triggers can automate cascading changes to related tables when a record is
modified or deleted.
Page 11 of 12
Advance Database System
Stored Procedure and Triggers

Example: Automatically delete orders when a customer is removed.

4. Enforcing Business Rules: Triggers can enforce specific business logic and rules directly in the
database.

Example: Prevent a user from being assigned to more than one department.

Advantages of Triggers

1. Automatic Execution:

➢ Triggers are automatically executed in response to specific events, ensuring that business
logic is applied consistently without manual intervention.

2. Data Integrity:

➢ They help maintain data integrity by enforcing rules and constraints, preventing invalid data
from being inserted or updated.

3. Auditing and Logging:

➢ Triggers can be used for auditing changes to the database, providing a historical record of
actions taken on data.
Page 12 of 12
Advance Database System
Stored Procedure and Triggers

4. Cascading Actions:

➢ They can automate cascading updates or deletes across related tables, ensuring referential
integrity without additional application logic.

5. Centralized Business Logic:

➢ Business rules can be implemented directly in the database, making them easier to manage
and enforce consistently across multiple applications.

6. Performance Optimization:

➢ Reduces application-level checks, which can streamline processes and improve


performance, especially for bulk operations.

Disadvantages of Triggers

1. Complexity:

➢ Triggers can make the database logic more complex and harder to understand, especially if
there are multiple triggers on the same table.

2. Debugging Difficulty:

➢ Triggers can be difficult to debug because they operate behind the scenes. Errors may not
surface immediately and can lead to unexpected behavior.

3. Performance Overhead:

➢ Excessive or poorly designed triggers can introduce performance overhead, especially if


they execute complex logic or involve large datasets.

4. Unintended Consequences:

➢ Triggers can lead to unintended side effects, such as recursive calls if a trigger modifies
data that causes the same trigger to fire again.

5. Portability Issues:

➢ Different database systems may have varying support for triggers, leading to potential
portability issues if applications need to be migrated.

6. Hidden Logic:

➢ Business logic implemented in triggers may not be immediately visible to developers and
users, leading to confusion about where certain rules are enforced.

You might also like