Triggers automatically execute when you perform actions like insert, update, or delete on a table.
Triggers can be used for auditing, validations, and automatic updates.
INSTEAD OF triggers replace the original action (like instead of deleting, soft-delete).
AFTER triggers execute after the original action is complete.
BEFORE triggers execute before the original action is complete.
SYNTAX;-
CREATE TRIGGER trigger_name
ON table_name
AFTER INSERT
AS
BEGIN
-- Trigger logic here
PRINT 'Row inserted in the table';
END;
BASIC SYNTAX;-
CREATE TRIGGER trigger_name
ON table_name
[AFTER | BEFORE | INSTEAD OF] [INSERT | UPDATE | DELETE]
AS
BEGIN
-- यहाँ पर आप वह कोड लिख सकते हैं जो ट्रिगर चलने पर निष्पादित होगा
PRINT 'यह ट्रिगर सफलतापूर्वक चला है';
END;
1.AFTER INSERT Trigger:
CREATE TRIGGER trgAfterInsert
ON Employees
AFTER INSERT
AS
BEGIN
-- यहाँ पर ऑडिट टेबल में इन्सर्ट की गई जानकारी लॉग की जा सकती है
INSERT INTO AuditTable (EmployeeID, Action)
SELECT EmployeeID, 'INSERT' FROM inserted;
PRINT 'नया रेकॉर्ड सफलतापूर्वक डाला गया और ऑडिट में रिकॉर्ड हुआ';
END;
=======================================================================
Q. Can we disable a trigger? If yes, how?
1. In SQL Server:
You can use the DISABLE TRIGGER
command to disable a specific trigger on a table or on the database.
Disabling a trigger on a table:
DISABLE TRIGGER TriggerName ON TableName;
Example:
DISABLE TRIGGER trgInsertEmployee ON Employees;
Disabling all triggers on a table:
DISABLE TRIGGER ALL ON TableName;
Example:
DISABLE TRIGGER ALL ON Employees;
Disabling a trigger on the entire database:
DISABLE TRIGGER TriggerName ON DATABASE;
Example:
DISABLE TRIGGER trgAuditLog ON DATABASE;

No comments: