SQL-Server Triggers  «Prev  Next»

Lesson 3 Types of triggers
Objective Temporary tables used to verify accuracy of trigger

How temporary tables can be used to verify the accuracy of a trigger in SQL Server 2022

Temporary tables can be used to verify the accuracy of SQL Server triggers in SQL Server 2022 , but with important limitations and best practices to be aware of:
✅ Why Use Temporary Tables for Trigger Testing
Temporary tables (`#temp`) are useful for isolated, repeatable tests. You can:
  • Simulate inserts, updates, or deletes into a base table.
  • Create triggers on that base table.
  • Capture the trigger’s logic outcomes (e.g., audit entries or business rule enforcement).
  • Check intermediate values and results step-by-step.

⚠️ But There’s a Catch
SQL Server does not support creating triggers on temporary tables. You cannot define a `CREATE TRIGGER` on a table like `#tempTable`.
However, here is how you can use them effectively:
✅ Recommended Strategy
  1. Create a permanent test table (e.g., TestTable) with the same structure as your target production table.
  2. Create the trigger on that permanent table.
  3. In your test session:
  • Insert test data into `TestTable`.
  • Use temporary tables to simulate or capture:
    • Audit rows written by the trigger.
    • Intermediate results.
    • Error messages or rollback actions.

🔄 Example: Testing an AFTER INSERT Trigger
-- 1. Create your test table
CREATE TABLE TestOrders (
    OrderID INT PRIMARY KEY,
    Amount DECIMAL(10, 2)
);

-- 2. Create a table to log trigger activity
CREATE TABLE #AuditLog (
    OrderID INT,
    AuditMessage NVARCHAR(255)
);

-- 3. Create the trigger
CREATE TRIGGER trg_TestOrders_Insert
ON TestOrders
AFTER INSERT
AS
BEGIN
    INSERT INTO #AuditLog (OrderID, AuditMessage)
    SELECT OrderID, 'Order inserted with amount ' + CAST(Amount AS NVARCHAR)
    FROM inserted;
END;

❌ The above will fail because the trigger is trying to insert into a temporary table, which is not visible in the trigger's context.

✅ Workaround
Use a permanent audit table for testing, and truncate it between runs:
-- Permanent audit table
CREATE TABLE AuditLogTest (
    OrderID INT,
    AuditMessage NVARCHAR(255)
);

-- Update the trigger to use AuditLogTest
CREATE TRIGGER trg_TestOrders_Insert
ON TestOrders
AFTER INSERT
AS
BEGIN
    INSERT INTO AuditLogTest (OrderID, AuditMessage)
    SELECT OrderID, 'Order inserted with amount ' + CAST(Amount AS NVARCHAR)
    FROM inserted;
END;

You can now:
  • Run test inserts into `TestOrders`
  • Query `AuditLogTest` to verify trigger behavior
  • Use temporary tables in your T-SQL scripts to orchestrate or stage your tests

✅ Conclusion
  • You can’t define triggers on temporary tables or reliably reference temporary tables inside triggers.
  • But you can use temporary tables for staging, simulation, and validation outside the trigger context.
  • For formal trigger testing, use permanent tables in a sandbox or test schema and clean them up afterward.

SQL-Server 2022
Three types of SQL Server triggers you listed are correct for SQL Server 2022. They are:
  • Insert Triggers: These fire when new data is inserted into a table (e.g., via an INSERT statement).
  • Delete Triggers: These fire when data is removed from a table (e.g., via a DELETE statement).
  • Update Triggers: These fire when data in a table is modified (e.g., via an UPDATE statement). You can also specify particular columns in the table that, when updated, will cause the trigger to fire.
Additional Details:
  • These triggers are classified as DML (Data Manipulation Language) triggers because they respond to data manipulation operations (INSERT, DELETE, UPDATE).
  • SQL Server 2022 also supports DDL (Data Definition Language) triggers, which fire in response to schema changes (e.g., CREATE, ALTER, DROP) and certain system stored procedures. However, these are distinct from the DML triggers you mentioned.

  • You can further categorize DML triggers as:
    • AFTER Triggers: Execute after the triggering action completes (e.g., after the insert, update, or delete operation).
    • INSTEAD OF Triggers: Execute in place of the triggering action, allowing you to override the default behavior.
  • For UPDATE triggers, SQL Server allows you to use the COLUMNS_UPDATED() function or UPDATE(column_name) clause to check if specific columns were modified, enabling more granular control.
Temporary Trigger Tables
SQL Server maintains two temporary tables for you to validate transactions before they are processed:
  1. Inserted: Populated with the data that was changed by the INSERT or UPDATE Transact-SQL statement.
  2. Deleted: Populated with the data that was changed by the DELETE or UPDATE Transact-SQL statement.

Trigger Types

The first ingredient in properly employing triggers is to understand the differences between AFTER and INSTEAD OF triggers. AFTER triggers are the same type of trigger that is available in previous versions of SQL Server. They are also known as "FOR triggers" or even simply as "triggers" since they were the only type of trigger available prior to SQL Server 2000. Let's first look at FOR triggers. You'll notice that the following trigger is created using the FOR keyword:
CREATE TRIGGER tr_Employees_U on Employees FOR UPDATE AS
   IF UPDATE(lastname)
   BEGIN
       RAISERROR ('cannot change lastname', 16, 1)
       ROLLBACK TRAN
       RETURN
   END
GO

It is important to know that your code cannot perform any inserts, updates, or deletes to or from the Inserted or Deleted tables. These tables can only be selected. If you want to get an idea of the data that is contained within the Inserted and Deleted special tables, you can select the data from each of these tables within the definition of the trigger itself. You must do it within the trigger because these tables are available only to the trigger, and not outside it. Also, make sure to remove these SELECT statements before you make your trigger live. You do not want your customers to see this. It is only for testing. Why are temporary tables important? The rest of this lesson shows how these special tables are used to validate changes to your tables before they are made permanent by SQL Server.
In the next lesson, the enforcement of business rules with triggers will be discussed.

SEMrush Software 3 SEMrush Banner 3