Gatilhos DDL

Criando e Otimizando Triggers no SQL Server

Florin Angelescu

Instructor

Definição e propriedades

Gatilhos DML

  • eventos associados a instruções DML INSERT, UPDATE, DELETE
  • usados com AFTER ou INSTEAD OF
  • vinculados a tabelas ou visões
  • tabelas especiais inserted e deleted

Gatilhos DDL

  • eventos associados a instruções DDL CREATE, ALTER, DROP
  • usados apenas com AFTER
  • vinculados a bancos de dados ou servidores
  • sem tabelas especiais
Criando e Otimizando Triggers no SQL Server

AFTER e FOR

CREATE TRIGGER DatabaseChangeLog
FOR CREATE_TABLE
[...]
Criando e Otimizando Triggers no SQL Server

AFTER e FOR

CREATE TRIGGER TrackDatabaseTables
FOR CREATE_TABLE
[...]

AFTER = FOR

Criando e Otimizando Triggers no SQL Server

Pré-requisitos de gatilhos DDL

  • Objeto de destino (servidor ou banco)
  • Descrição do gatilho
  • Eventos que disparam o gatilho (DDL)
  • Nome do gatilho
  • DATABASE
  • Tabela de log com mudanças de definição
  • CREATE_TABLE,ALTER_TABLE,DROP_TABLE
  • TrackTableChanges
Criando e Otimizando Triggers no SQL Server

Definição de gatilho DDL

CREATE TRIGGER TrackTableChanges

ON DATABASE
FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS INSERT INTO TablesChangeLog (EventData, ChangedBy) VALUES (EVENTDATA(), USER);
Criando e Otimizando Triggers no SQL Server

Impedindo eventos de disparo para gatilhos DML

CREATE TRIGGER PreventTableDeletion
ON DATABASE
FOR DROP_TABLE

AS RAISERROR ('You are not allowed to remove tables from this database.', 16, 1); ROLLBACK;
Criando e Otimizando Triggers no SQL Server

Vamos praticar!

Criando e Otimizando Triggers no SQL Server

Preparing Video For Download...