Skip to the workspace
Pebellslearn by building
Database Fundamentals  ›  Capstone Project

Stored Procedures and Triggers — Code Inside the Database

Stored Procedures 14 minA stored procedure is named SQL you call explicitly, while a trigger runs automatically when rows in its table change.

aspnet core / Stored Procedures and Triggers — Code Inside the Database

Explore each scene at your own pace.

01 · The rule

The rule

Stored Procedures and Triggers — Code Inside the Database

Most of ReadingRoom's logic lives in C#. But some jobs sit better next to the data: a heavy report that crunches thousands of loans, or an audit record that must be written no matter which program deletes a loan. Databases can hold code for exactly these jobs. (Examples use SQL Server's T-SQL, common in .NET shops; PostgreSQL has the same ideas with different syntax.)

The rule

A procedure runs when you call it; a trigger runs when data changes.

A stored procedure is named, saved SQL with parameters:

CREATE PROCEDURE dbo.TopBooks @Since date
AS
BEGIN
    SELECT TOP 10 b.Title, COUNT(*) AS Loans
    FROM Loans l JOIN Books b ON b.Id = l.BookId
    WHERE l.LoanedOn >= @Since
    GROUP BY b.Title
    ORDER BY COUNT(*) DESC;
END;

You run it with EXEC dbo.TopBooks @Since = '2025-01-01';. From C#, Dapper calls it directly:

var top = await connection.QueryAsync<BookCount>(
    "dbo.TopBooks", new { Since = since },
    commandType: CommandType.StoredProcedure);

A trigger is attached to a table and fires on INSERT, UPDATE or DELETE. Nobody calls it:

CREATE TRIGGER trg_Loans_Audit ON Loans
AFTER DELETE
AS
BEGIN
    INSERT INTO LoanAudit (LoanId, DeletedAt)
    SELECT Id, SYSUTCDATETIME() FROM deleted;
END;

Inside a SQL Server trigger, the deleted and inserted pseudo-tables hold the affected rows. A single statement can touch many rows, so a trigger must handle sets, not one row.

Why use them: less data sent over the network, one shared rule for every program using the database. Why be careful: the logic is hidden from anyone reading the C# code, harder to test, and tied to one database vendor.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.