Prompt
CREATE TRIGGER Log_EmployeeInsert
ON Employee
AFTER INSERT
AS
INSERT INTO LogTable
SELECT 'New Employee data inserted on ' + CONVERT(VARCHAR(20), GETDATE());
GO
Answer
Explanation of SQL Trigger Code
The given code snippet is a SQL trigger that is designed to log information into another table (LogTable
) after a new record is inserted into the Employee
table.
Components of the Trigger
Trigger Name:
Log_EmployeeInsert
- Name of the trigger created.Trigger Event:
AFTER INSERT
- Specifies that the trigger will fire after an insertion operation on theEmployee
table.Trigger Action:
INSERT INTO LogTable SELECT 'New Employee data inserted on ' + CONVERT(VARCHAR(20), GETDATE());
- This action inserts a new row into the
LogTable
table. - The inserted row contains a string indicating that new employee data has been inserted, along with the current date and time.
- This action inserts a new row into the
Explanation
- This trigger ensures that every time a new record is inserted into the
Employee
table, a corresponding entry will be added to theLogTable
to track this event. - The
CONVERT(VARCHAR(20), GETDATE())
function is used to convert the current date and time into a varchar format before inserting it into theLogTable
.
Example
Suppose we insert a new record into the Employee
table:
INSERT INTO Employee (EmployeeName) VALUES ('John Doe');
After this insertion, the trigger will fire and add a new entry into the LogTable
with a message like:
'New Employee data inserted on 2023-10-25 14:30:00'
Description
Explanation and example of a SQL trigger code designed to log information into a separate table after a new employee record is inserted, capturing event details with timestamps.