Roadmap › SQL Server & T-SQL › Module: Programmability
Lessons in this course (19)

12. Views, triggers and temporary objects

IntermediateMediumLesson 12 of 19
sql
CREATE OR ALTER VIEW dbo.vw_ActiveEmployees WITH SCHEMABINDING AS
SELECT EmpId, FullName, DeptId FROM dbo.Employees WHERE IsActive = 1;
-- Indexed (materialised) view: SCHEMABINDING + unique clustered index
sql
CREATE OR ALTER TRIGGER dbo.trg_Employees_Audit ON dbo.Employees
AFTER UPDATE AS
BEGIN
    SET NOCOUNT ON;
    INSERT INTO dbo.SalaryAudit (EmpId, OldSalary, NewSalary, ChangedAt)
    SELECT d.EmpId, d.Salary, i.Salary, SYSUTCDATETIME()
    FROM inserted i JOIN deleted d ON d.EmpId = i.EmpId
    WHERE i.Salary <> d.Salary;            -- handle MULTI-ROW updates, not just one row
END;

Triggers: AFTER (DML), INSTEAD OF (often on views), DDL triggers, logon triggers. Magic tables inserted / deleted. Keep them small; they hide logic and run inside the caller's transaction.

Temp table #tTable variable @tCTE
ScopeSession/proc (tempdb)Batch/procSingle statement
StatisticsYesNo column stats (2019: deferred compilation improves row estimates)n/a
IndexesAnyInline PK/unique/index definitionsn/a
Transaction rollbackData rolled backData not rolled backn/a
Good forLarger intermediate setsSmall setsReadability/recursion

Global temp table ##t is visible to all sessions.