In this article, what is INSERT TRIGGER and how to use it? I will talk about this.
First of all, we need to create a function or procedure before creating a trigger.
The purpose of doing this is that we will be performing the operation within the create trigger command using that function.
I think it will be better understood by making an example of the insert trigger.
When the insertion operation of the veliler table is done, we will make a trigger that writes the id, adi, soyadi columns in which parents table and which user made this insertion, when he did it and what action he did, to the parents audit table.
First, we create a table named Veliler_audit, which will keep the log of insertions.
1 2 3 4 5 6 7 8 9 |
CREATE TABLE "Veliler_Audit" ( "Velilerid" INT NOT NULL, "İsim" VARCHAR(20) NOT NULL, "Soyisim" VARCHAR(20) NOT NULL, "UserName" VARCHAR(20) NOT NULL, "Tarih" VARCHAR(20) NOT NULL, "İşlem" VARCHAR(20) NOT NULL ); |
After creating our table, we need to create a function as follows to add our data to the parents_audit table.
Here, in the returns section, you can see that we used the Returns trigger command.
The reason for this is because this function will be used in the trigger.
1 2 3 4 5 6 7 8 9 |
CREATE OR REPLACE FUNCTION veliler_insert_trigger_fnc() RETURNS trigger AS $$ BEGIN INSERT INTO "Veliler_Audit" ( "Velilerid", "İsim", "Soyisim","UserName" ,"Tarih","İşlem") VALUES(NEW."no",NEW."adi",NEW."soyadi",current_user,current_date,'İnsertt'); RETURN NEW; END; $$ LANGUAGE 'plpgsql'; |
After creating our function, we create the trigger we specified as follows.
1 2 3 4 5 |
CREATE TRIGGER veliler_insert_trigger AFTER INSERT ON "veliler" FOR EACH ROW EXECUTE PROCEDURE veliler_insert_trigger_fnc(); |
Let’s add data to the Veliler table.
1 2 3 |
INSERT INTO public.veliler( no, adi, soyadi, evtelefon) VALUES (15, 'f', 'a', 053212); |
We added our data and let’s check if data has been added to our veliler_Audit table.