Good Place. Good Things. Good Time.

SQL DELETE Trigger

SQL DELETE Trigger

Introduction to SQL DELETE Trigger

DELETE Trigger is a data manipulation language (DML) trigger in SQL. A stored procedure on a database object gets invoked automatically instead of before or after a DELETE command has been successfully executed on the said database table. DELETE Triggers are usually used in scenarios when we want to track details of data removal from a table in a separate audit table or when we want to perform cascading delete operations, like if we delete a row from table1, then it should be deleted from table2 as well.

Syntax and parameters

The basic syntax used for writing a DELETE Trigger in SQL is as follows :

CREATE TRIGGER [schema_name. ] trigger_name ON table_name
{AFTER| BEFORE | INSTEAD OF } DELETE
AS
{SQL statements}

The arguments used in the above-mentioned syntax are as follows :

schema_name: schema_name here corresponds to the name of the schema where the new

A delete trigger will be created. The schema name is optional, but when we do not mention the schema_name, the trigger gets created in the default schema.

trigger_name: trigger_name is the name of the new delete trigger which is being created.

table_name: table_name is the name of the database table on which the new A delete trigger will be created.

AFTER | BEFORE | INSTEAD OF: This argument is to register the time of DELETE trigger invocation concerning the execution of the DELETE statement.

SQL statements: SQL statements are a set of SQL operations that form the body of a DELETE trigger.

Having discussed the syntax and parameters used for creating DELETE triggers in SQL, let us try a few examples to understand it in great detail.

Examples of SQL DELETE Trigger

To illustrate DELETE Triggers’ work in SQL, let us create two dummy tables called students and students_audit, respectively.

CREATE TABLE students(
roll_no int NOT NULL PRIMARY KEY,
student_name VARCHAR(255),
degree_major VARCHAR(255) NOT NULL,
degree_year VARCHAR(255),
society VARCHAR(255)
);

SQL DELETE Trigger output 1

Having created the student’s table. Let us insert a few records in it to work with.

INSERT INTO [practice_db].[dbo].[students]
([roll_no]
,[student_name]
,[degree_major]
,[degree_year]
,[society])
VALUES
(1,'Mohith K','Computer Science Engineering','IV','Dramatics'),
(2,'Ayesha Khan','Electrical Engineering','I','Music'),
(3,'Kylie Green','Computer Science Engineering','III','Choreography'),
(4,'Alisha Rojer','Chemical Engineering','III','Music'),
(5,'Andy Bernard','Geosciences','IV','Dramatics')
GO

SQL DELETE Trigger output 2

Next, let us create the students_audit table, which is similar to the student’s table but with two additional columns.

CREATE TABLE students_audit(
roll_no int NOT NULL PRIMARY KEY,
student_name VARCHAR(255),
degree_major VARCHAR(255) NOT NULL,
degree_year VARCHAR(255),
society VARCHAR(255),
deleted_by VARCHAR(50),
deleted_at DATETIME
);

SQL DELETE Trigger output 3

Let’s leave this table empty for the time being.

Example #1

Create a DELETE Trigger on the student’s table that deletes records from the student’s table and insert the deleted records with servername and time of deletion on a separate table called “students_audit”.

Code:

CREATE TRIGGER AfterDELETETrigger on students
AFTER DELETE
AS DECLARE
@roll_no INT,
@student_name VARCHAR(255),
@degree_major VARCHAR(255),
@degree_year VARCHAR(255),
@society VARCHAR(255);
SELECT @roll_no = d.roll_no FROM DELETED d;
SELECT @student_name = d.student_name FROM DELETED d;
SELECT @degree_major = d.degree_major FROM DELETED d;
SELECT @degree_year = d.degree_year FROM DELETED d;
SELECT @society = d.society FROM DELETED d;
INSERT INTO students_audit(
[roll_no]
,[student_name]
,[degree_major]
,[degree_year]
,[society]
,[Deleted_by]
,[Deleted_at])
VALUES (@roll_no,
@student_name,
@degree_major,
@degree_year,
@society,
CAST( SERVERPROPERTY('ServerName') AS VARCHAR(50)),
GETDATE());
GO

SQL DELETE Trigger output 4

The query was executed successfully. The newly created AfterDELETETrigger has been mentioned under the Triggers head in the object explorer.

SQL DELETE Trigger output 5

Now let us check if the “AfterDELETETrigger” serves the intended purpose. Here is a DELETE statement on the student’s table that tries to delete a row with roll_no = ‘3’.

DELETE FROM students
WHERE roll_no = '3';

SQL DELETE Trigger output 6

Two rows got affected. That’s true, one row of the student’s table got removed, and one row got inserted in the students_audit table. Let’s check for ourselves using a SELECT statement.

SELECT * FROM students_audit;

output 7

The row with roll_no = ‘3’ has been successfully inserted in the students_audit table.

Let’s try one more DELETE statement. Here, we are deleting one or more rows in the student’s table where the student belongs to ‘Dramatics’ and has a degree_major starting with ‘Geo’.

DELETE FROM students
WHERE society = 'Dramatics' AND degree_major LIKE 'Geo%';

output 8

Similar to the previous query, we have successfully deleted and inserted the concerned row from(in) the students and students_audit table respectively.

SELECT * FROM students;
SELECT * FROM students_audit;

output 9

Example #2

Create a delete trigger that, on executing a delete statement on the student’s table, does not delete the row from it but instead deletes it from the students_audit table.

Code:

CREATE TRIGGER InsteadDELETETrigger
ON students
INSTEAD OF DELETE
AS
DELETE FROM students_audit
WHERE roll_no IN(SELECT deleted.roll_no FROM deleted)
GO

output 10

The trigger has been successfully created. It is mentioned under the triggers head of the student’s table in object explorer.

output 11

To undo the work of the AfterDELETETrigger, let us insert back the following row in the student’s table (just for the sake of this example).

INSERT INTO [practice_db].[dbo].[students]
([roll_no]
,[student_name]
,[degree_major]
,[degree_year]
,[society])
VALUES
(3,'Kylie Green','Computer Science Engineering','III','Choreography')
GO

output 12

The present status of students and students_audit table is as follows:

SELECT * FROM students;
SELECT * FROM students_audit;

output 13

In the previous steps, we have created the ‘InsteadDELETETrigger’. Let’s check its functionality by executing a DELETE statement on the student’s table.

DELETE FROM students
WHERE society = 'Choreography';

output 14

Two rows got affected, but as intended, the row with society = ‘Choreography’ has been successfully deleted from the students_audit table instead of the student’s table.

SELECT * FROM students;
SELECT * FROM students_audit;

output 15

Conclusion

DELETE Trigger is a DDL trigger that gets fired automatically once a DELETE statement has been successfully on a database object.

Recommended Articles

This is a guide to SQL DELETE Trigger. Here we discuss the Basic syntax used for writing a DELETE Trigger along with the Examples. You may also have a look at the following articles to learn more –

  1. SQL ORDER BY DATE
  2. SQL Table Partitioning
  3. SQL NOT Operator
  4. SQL ORDER BY Ascending

The post SQL DELETE Trigger appeared first on EDUCBA.

Read original article here: SQL DELETE Trigger

Read original article here: SQL DELETE Trigger



Disclaimers and Denial of responsibility..!

Denial of responsibility! TheTopMag.com is an automatic aggregator of all media around the world. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – jamesonline999@gmail.com . The content will be deleted within 72 hours.
You might also like
Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.