Introdução

Criando e Otimizando Triggers no SQL Server

Florin Angelescu

Instructor

O que é um trigger?

  • Tipo especial de procedimento armazenado
  • Executado quando ocorre um evento no servidor de banco de dados

Como um Trigger funciona

Criando e Otimizando Triggers no SQL Server

Tipos de trigger (com base nos comandos T-SQL)

  • Triggers de Data Manipulation Language (DML)
    • Instruções INSERT, UPDATE ou DELETE
  • Triggers de Data Definition Language (DDL)
    • Instruções CREATE, ALTER ou DROP
  • Triggers de logon
    • Eventos LOGON
Criando e Otimizando Triggers no SQL Server

Tipos de trigger (com base no comportamento)

  • Trigger AFTER

    • A instrução original é executada
    • Instruções adicionais são acionadas
  • Exemplos de uso

    • Reconstruir um índice após um grande insert
    • Notificar o admin quando dados forem atualizados
Criando e Otimizando Triggers no SQL Server

Tipos de trigger (com base no comportamento)

  • Trigger INSTEAD OF

    • A instrução original não é executada
    • Uma instrução substituta é executada
  • Exemplos de uso

    • Evitar inserções
    • Evitar atualizações
    • Evitar exclusões
    • Evitar modificações de objetos
    • Notificar o admin
Criando e Otimizando Triggers no SQL Server

Definição de trigger (com AFTER)

-- Create the trigger by giving it a descriptive name
CREATE TRIGGER ProductsTrigger

-- The trigger needs to be attached to a table ON Products
-- The trigger behavior type AFTER INSERT
-- The beginning of the trigger workflow AS
-- The action executed by the trigger PRINT ('An insert of data was made in the Products table.');
Criando e Otimizando Triggers no SQL Server

Definição de trigger (com INSTEAD OF)

-- Create the trigger by giving it a descriptive name
CREATE TRIGGER PreventDeleteFromOrders
-- The trigger needs to be attached to a table
ON Orders
-- The trigger behavior type
INSTEAD OF DELETE
-- The beginning of the trigger workflow
AS
-- The action executed by the trigger
PRINT ('You are not allowed to delete rows from the Orders table.');
Criando e Otimizando Triggers no SQL Server

AFTER vs. INSTEAD OF

CREATE TRIGGER MyFirstAfterTrigger
ON Table1
-- Triggered after 
-- the firing event (UPDATE)
AFTER UPDATE
AS
{trigger_actions_section};
CREATE TRIGGER MyFirstInsteadOfTrigger
ON Table2
-- Triggered instead of 
-- the firing event (UPDATE)
INSTEAD OF UPDATE
AS
{trigger_actions_section};
Criando e Otimizando Triggers no SQL Server

Vamos praticar!

Criando e Otimizando Triggers no SQL Server

Preparing Video For Download...