DB2 exemplos simples - CREATE TRIGGER



Desenvolvido por DORNELLES Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

DB2 exemplos simples - CREATE TRIGGER

Resumo: neste tutorial, você aprenderá a usar a instrução Db2 CREATE TRIGGER para criar novos acionadores no banco de dados.

Introdução à instrução Db2 CREATE TRIGGER

A instrução CREATE TRIGGER permite criar um novo gatilho ou substituir um gatilho existente no banco de dados.

A sintaxe básica para a instrução CREATE TRIGGER é a seguinte:

Summary: in this tutorial, you will learn how to use the Db2 CREATE TRIGGER statement to create new triggers in the database.

Introduction to Db2 CREATE TRIGGER statement

The CREATE TRIGGER statement allows you to create a new trigger or replace an existing trigger in the database.

The basic syntax for the CREATE TRIGGER statement is the following:


CREATE [OR REPLACE] TRIGGER trigger_name

       [NO CASCADE] {AFTER | BEFORE | INSTEAD OF} trigger_event
	
       ON { table_name |view_name }
	
       REFERENCING {OLD AS | NEW AS | OLD TABLE AS | NEW TABLE AS}
	
       {correlation_name |identifier}
	
      {FOR EACH ROW | FOR EACH STATEMENT}
	
      action;

Nesta sintaxe:

  • Primeiro, especifique o nome do acionador após as palavras-chave CREATE TRIGGER.
    Se você usar CREATE OR REPLACE TRIGGER, o Db2 criará o gatilho se ele não existir ou substituirá caso o gatilho já exista.

  • Segundo, especifique o evento que ativa o gatilho, por exemplo, INSERT, UPDATE ou DELETE.

  • Terceiro, identifique o nome da tabela ou exibição na qual o gatilho está definido.

  • Quarto, especifique um nome de correlação que identifique o estado da linha antes de acionar a operação.

  • Quinto, especifique um nome de tabela temporária que identifique o conjunto de linhas afetadas antes de acionar a operação.

  • Sexto, especifique a ação a ser executada quando um gatilho é acionado.

In this syntax:

  • First, specify the name of the trigger after the CREATE TRIGGER keywords.
    If you use CREATE OR REPLACE TRIGGER, Db2 will create the trigger if it does not exist or replace in case the trigger already exists.

  • Second, specify the event that activates the trigger e.g., INSERT, UPDATE, or DELETE.

  • Third, identify the name of the table or view on which the trigger is defined.

  • Fourth, specify a correlation name that identifies the row state before triggering the operation.

  • Fifth, specify a temporary table name that identifies the set of affected rows before triggering the operation.

  • Sixth, specify the action to perform when a trigger is fired.


Exemplo de Db2 CREATE TRIGGER

Vamos ver um exemplo de uso da instrução CREATE TRIGGER para criar um gatilho após a inserção.

Primeiro, crie uma nova tabela chamada funcionários para armazenar os dados dos funcionários:

Db2 CREATE TRIGGER example

Let’s see an example of using the CREATE TRIGGER statement to create an after insert trigger.

First, create a new table named employees to store employee data:



CREATE TABLE employees(

       employee_id INT GENERATED ALWAYS AS IDENTITY NOT NULL,
	   
       first_name VARCHAR(100) NOT NULL,
	   
       last_name VARCHAR(100) NOT NULL,
	   
       gender CHAR(1) NOT NULL,
	   
       dob DATE NOT NULL,
	   
       salary DEC(10,2) NOT NULL,
	   
       start_date DATE,
	   
       PRIMARY KEY(employee_id),
	   
       CHECK(salary > 0),
	   
       CHECK(gender = 'F' OR gender = 'M')
);

Segundo, crie uma nova tabela hr_stats e insira uma linha na tabela hr_stats.
A tabela hr_stats tem uma coluna que armazena o total de funcionários:

Second, create a new table hr_stats and insert a row into the hr_stats table.
The hr_stats table has one column that store total headcount:

CREATE TABLE hr_stats(

       headcount INT NOT NULL DEFAULT 0,
	   
       CHECK(headcount>=0)
   
);

INSERT INTO hr_stats(headcount)
 
       VALUES(0);

Terceiro, crie um novo gatilho chamado update_headcount que aumente o número de funcionários em um depois que um novo funcionário for inserido na tabela de funcionários

Third, create a new trigger named update_headcount that increases the headcount by one after a new employee is inserted into the employees table

CREATE OR REPLACE TRIGGER update_headcount 

       AFTER INSERT ON employees
   
       FOR EACH ROW MODE DB2SQL 
   
       UPDATE hr_stats 
   
       SET headcount = headcount + 1;

Quarto, insira dois funcionários na tabela de funcionários:

Fourth, insert two employees to the employees table:

INSERT INTO 

       EMPLOYEES(first_name, last_name, gender, dob, start_date, salary)
   
VALUES
	   
      ('John','Doe','M','1990-12-15','2019-06-07',120000),
      ('Jane','Doe','F','1992-06-12','2019-06-07',120000);

O acionador update_headcount foi executado duas vezes.
Por fim, visualize o conteúdo da tabela hr_stats para verificar se o gatilho foi executado ou não.

The trigger update_headcount were executed twice.
Finally, view the contents of the hr_stats table to verify whether the trigger has been executed or not.

SELECT * FROM hr_stats;

Aqui está a saída:

Here is the output:

HEADCOUNT
---------
2

Neste tutorial, você aprendeu como usar a instrução Db2 CREATE TRIGGER para criar um novo acionador no banco de dados.

In this tutorial, you have learned how to use the Db2 CREATE TRIGGER statement to create a new trigger in the database.