Reputation: 57
Using Microsoft SQL Server Management Studio.
I need help creating a quick FOR INSERT trigger for a table called dbo.Employees using the popular Northwind sample database. The trigger should default the 'Region' column in dbo.Employees to 'WA' if no region was inserted.
And if the region inserted was 'WA', then the 'Country' column should default to 'USA'. Any help would be much appreciated.
The employees table if it helps:
Upvotes: 0
Views: 200
Reputation: 14077
Like Gordon Linoff said, this should be a constraint, but if you really needs to get this done using triggers, this will work:
CREATE TRIGGER dbo.EmployeesTrigger ON dbo.Employees
FOR INSERT
AS
BEGIN
UPDATE E
SET E.Country = CASE I.Country
WHEN 'WA' THEN 'USA'
ELSE ISNULL(I.Country, 'WA')
END
FROM dbo.Employees AS E
INNER JOIN INSERTED AS I
ON I.EmployeeID = E.EmployeeID;
END
It will update record once something has been inserted.
Upvotes: 2