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 indexsql
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 #t | Table variable @t | CTE | |
|---|---|---|---|
| Scope | Session/proc (tempdb) | Batch/proc | Single statement |
| Statistics | Yes | No column stats (2019: deferred compilation improves row estimates) | n/a |
| Indexes | Any | Inline PK/unique/index definitions | n/a |
| Transaction rollback | Data rolled back | Data not rolled back | n/a |
| Good for | Larger intermediate sets | Small sets | Readability/recursion |
Global temp table ##t is visible to all sessions.