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;
![Trigger Enable & Disable in SQL](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5eGhwN2nH_VeYvb-n-oKMz58cVO8p09D6pPJgDw7vilDS6YN4NG6AgoZ1yH4fFCoLn9HBsb-ltAqBhch625npZ1vlzJP_PnwxfudjOp-pbj7WOkAb151g_XJTCP1NUAeS_EOH2lAsH9eHgeYy9I0r0_q3QTeKQDdUgNeoT-CQBm0F0BVSM-hlz9gqaM7R/s72-c/How%20to%20enable%20disable%20trigger%20in%20Sql.png)
No comments: