Close Menu
  • Home
  • Featured
  • Technologies
    • Frontend
      • JavaScript
      • AngularJS
      • ReactJS
      • HTML5 & CSS3
    • Backend
      • Java
      • PHP
      • C#
      • Node.js
      • Python
    • DevOps
      • Docker
      • Kubernetes
      • Gitlab
    • Databases
      • SQL
      • MySQL
      • MongoDB
      • SQLite
    • Cloud
      • AWS
      • Azure
      • GCP
    • Frameworks
      • .NET Core
      • .NET
      • Laravel
      • Bootstrap
    • S/W Testing
      • Selenium
      • PostMan
      • JMeter
  • Resources
  • Shop

Subscribe to Updates

Get the latest creative news from FooBar about art, design and business.

What's Hot

Deep Dive into Docker Architecture

October 1, 2025

What is MVC in Laravel?

July 5, 2025

 Data Protection: Building Trust, Ensuring Compliance, and Driving Growth

June 4, 2025
Facebook X (Twitter) Instagram LinkedIn WhatsApp YouTube
  • Featured

    Deep Dive into Docker Architecture

    October 1, 2025

    What is MVC in Laravel?

    July 5, 2025

     Data Protection: Building Trust, Ensuring Compliance, and Driving Growth

    June 4, 2025

    A Beginner’s Guide to Virtualization and Containers.

    May 18, 2025

    CI/CD: From Code Commit to Production

    May 9, 2025
  • Tech
  • Gadgets
  • Get In Touch
Facebook X (Twitter) Instagram YouTube WhatsApp
Learn with MashLearn with Mash
  • Home
  • Featured

    Deep Dive into Docker Architecture

    October 1, 2025

    What is MVC in Laravel?

    July 5, 2025

    Understanding Attributes in DBMS

    April 11, 2025

    VPN in Google Cloud Platform (GCP)

    April 4, 2025

    Automate 90% of Your Work 🚀with AI Agents 🤖 (Real Examples & Code Inside)

    April 2, 2025
  • Technologies
    • Frontend
      • JavaScript
      • AngularJS
      • ReactJS
      • HTML5 & CSS3
    • Backend
      • Java
      • PHP
      • C#
      • Node.js
      • Python
    • DevOps
      • Docker
      • Kubernetes
      • Gitlab
    • Databases
      • SQL
      • MySQL
      • MongoDB
      • SQLite
    • Cloud
      • AWS
      • Azure
      • GCP
    • Frameworks
      • .NET Core
      • .NET
      • Laravel
      • Bootstrap
    • S/W Testing
      • Selenium
      • PostMan
      • JMeter
  • Resources
  • Shop
Learn with MashLearn with Mash
Home » SQL Triggers, Stored Procedure and Views
Programming

SQL Triggers, Stored Procedure and Views

Edwin MachariaBy Edwin MachariaFebruary 6, 2025Updated:February 6, 2025No Comments4 Mins Read
Facebook Twitter Pinterest LinkedIn Tumblr Email
Share
Facebook Twitter LinkedIn WhatsApp Copy Link

1. SQL Triggers

What is an SQL Trigger?

A trigger is a special type of stored procedure that automatically executes in response to certain events on a table or a view. Triggers are primarily used for enforcing business rules, maintaining data integrity, and automating system tasks.

Types of Triggers in SQL Server

1. DML Triggers (Data Manipulation Language Triggers)

These triggers are fired when an INSERT, UPDATE, or DELETE operation occurs on a table.

  • AFTER Trigger (FOR Trigger): Executes after the triggering action is completed.
  • INSTEAD OF Trigger: Executes before the triggering action and can replace the action.

2. DDL Triggers (Data Definition Language Triggers)

These triggers fire when schema-related events occur, such as CREATE, ALTER, or DROP operations.

3. Logon Triggers

These triggers execute when a user logs into the SQL Server instance. They are useful for security and auditing purposes.

Example of a DML AFTER Trigger

CREATE TRIGGER trg_AfterInsert
ON Employees
AFTER INSERT
AS
BEGIN
    INSERT INTO EmployeeAudit(EmployeeID, Action, ActionDate)
    SELECT ID, 'INSERT', GETDATE() FROM inserted;
END;

📌 Explanation:
Whenever a new record is inserted into the Employees table, an entry is logged into the EmployeeAudit table.

Example of an INSTEAD OF Trigger

CREATE TRIGGER trg_InsteadOfDelete
ON Employees
INSTEAD OF DELETE
AS
BEGIN
    PRINT 'Deletion is not allowed on this table!';
END;

📌 Explanation:
If someone tries to delete a record from the Employees table, the trigger will block the action and display a message instead.


2. SQL Stored Procedures

What is a Stored Procedure?

A stored procedure is a reusable set of SQL statements that can be executed as a unit. Stored procedures improve performance, security, and maintainability of database operations.

Advantages of Stored Procedures

✅ Improved Performance – Precompiled SQL statements reduce execution time.
✅ Code Reusability – Can be used multiple times in different parts of an application.
✅ Security – Permissions can be granted at the stored procedure level instead of table level.
✅ Transaction Management – Allows complex operations with BEGIN TRANSACTION and ROLLBACK features.

Basic Example of a Stored Procedure

CREATE PROCEDURE GetEmployeeDetails
    @EmpID INT
AS
BEGIN
    SELECT * FROM Employees WHERE ID = @EmpID;
END;

📌 Usage:

EXEC GetEmployeeDetails @EmpID = 101;

Stored Procedure with Multiple Parameters

CREATE PROCEDURE UpdateEmployeeSalary
    @EmpID INT,
    @NewSalary DECIMAL(10,2)
AS
BEGIN
    UPDATE Employees
    SET Salary = @NewSalary
    WHERE ID = @EmpID;
END;

📌 Usage:

EXEC UpdateEmployeeSalary @EmpID = 105, @NewSalary = 75000.00;

Stored Procedure with Transaction Handling

CREATE PROCEDURE TransferFunds
    @SenderID INT,
    @ReceiverID INT,
    @Amount DECIMAL(10,2)
AS
BEGIN
    BEGIN TRANSACTION;
    BEGIN TRY
        -- Deduct from sender
        UPDATE Accounts SET Balance = Balance - @Amount WHERE AccountID = @SenderID;

        -- Add to receiver
        UPDATE Accounts SET Balance = Balance + @Amount WHERE AccountID = @ReceiverID;

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        PRINT 'Transaction failed!';
    END CATCH;
END;

📌 Usage:

EXEC TransferFunds @SenderID = 101, @ReceiverID = 202, @Amount = 500.00;

📌 Explanation:
If an error occurs during the transaction, the rollback ensures data consistency.


3. SQL Views

What is a View?

A view is a virtual table that is derived from one or more tables but does not store data itself. Views help in simplifying complex queries, enforcing security, and improving performance.

Types of Views

1. Simple View

A view based on a single table without aggregates or joins.

2. Complex View

A view that combines multiple tables using JOIN, aggregates, and functions.

3. Indexed View (Materialized View in some DBMS)

A view that physically stores the result set and improves performance for large datasets.

Basic Example of a View

CREATE VIEW EmployeeView AS
SELECT ID, Name, Department, Salary FROM Employees;

📌 Usage:

SELECT * FROM EmployeeView;

📌 Explanation:
This view helps users query employee details without accessing the main Employees table directly.

Example of a Complex View

CREATE VIEW EmployeeDepartmentView AS
SELECT e.ID, e.Name, d.DepartmentName, e.Salary
FROM Employees e
JOIN Departments d ON e.DepartmentID = d.ID;

📌 Usage:

SELECT * FROM EmployeeDepartmentView WHERE DepartmentName = 'HR';

📌 Explanation:
This view joins two tables (Employees and Departments) to present a meaningful dataset.

Example of an Indexed View

CREATE VIEW TotalSalesView WITH SCHEMABINDING AS
SELECT SalesPersonID, SUM(SalesAmount) AS TotalSales
FROM Sales
GROUP BY SalesPersonID;
GO
CREATE UNIQUE CLUSTERED INDEX IDX_TotalSales ON TotalSalesView(SalesPersonID);

📌 Explanation:

  • The WITH SCHEMABINDING option ensures the underlying tables cannot be modified without altering the view first.
  • The indexed view improves query performance for aggregate calculations.

Conclusion

📌 Triggers are automatic event-based stored procedures useful for maintaining data integrity.
📌 Stored Procedures are precompiled sets of SQL statements that enhance performance and security.
📌 Views provide a simplified and secure way to access complex data structures.


featured
Share. Facebook Twitter LinkedIn WhatsApp
Edwin Macharia
  • Website

Software Engineer || Database Administrator || DevOps Developer || Certified Scrum Master

Related Posts

Deep Dive into Docker Architecture

October 1, 2025

What is MVC in Laravel?

July 5, 2025

 Data Protection: Building Trust, Ensuring Compliance, and Driving Growth

June 4, 2025

A Beginner’s Guide to Virtualization and Containers.

May 18, 2025
Add A Comment
Leave A Reply Cancel Reply

Editors Picks

Deep Dive into Docker Architecture

October 1, 2025

What is MVC in Laravel?

July 5, 2025

 Data Protection: Building Trust, Ensuring Compliance, and Driving Growth

June 4, 2025

A Beginner’s Guide to Virtualization and Containers.

May 18, 2025
Top Reviews
Advertisement
Learn with Mash
Facebook X (Twitter) Instagram YouTube LinkedIn WhatsApp
  • Home
  • Tech
  • Gadgets
  • Mobiles
  • Privacy & Policy
© 2026 Edwin Macharia. Designed by Movosoft Technologies.

Type above and press Enter to search. Press Esc to cancel.

Ad Blocker Enabled!
Ad Blocker Enabled!
Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.