Как отключить триггер в sql
Перейти к содержимому

Как отключить триггер в sql

  • автор:

Триггеры

Триггеры представляют специальный тип хранимой процедуры, которая вызывается автоматически при выполнении определенного действия над таблицей или представлением, в частности, при добавлении, изменении или удалении данных, то есть при выполнении команд INSERT, UPDATE, DELETE.

Формальное определение триггера:

Для создания триггера применяется выражение CREATE TRIGGER , после которого идет имя триггера. Как правило, имя триггера отражает тип операций и имя таблицы, над которой производится операция.

Каждый триггер ассоциируется с определенной таблицей или представлением, имя которых указывается после слова ON .

Затем устанавливается тип триггера. Мы можем использовать один из двух типов:

AFTER : выполняется после выполнения действия. Определяется только для таблиц.

INSTEAD OF : выполняется вместо действия (то есть по сути действие — добавление, изменение или удаление — вообще не выполняется). Определяется для таблиц и представлений

После типа триггера идет указание операции, для которой определяется триггер: INSERT , UPDATE или DELETE .

Для триггера AFTER можно применять сразу для нескольких действий, например, UPDATE и INSERT. В этом случае операции указываются через запятую. Для триггера INSTEAD OF можно определить только одно действие.

И затем после слова AS идет набор выражений SQL, которые собственно и составляют тело триггера.

Создадим триггер. Допустим, у нас есть база данных productsdb со следующим определением:

Определим триггер, который будет срабатывать при добавлении и обновлении данных:

Допустим, в таблице Products хранятся данные о товарах. Но цена товара нередко содержит различные надбавки типа налога на добавленную стоимость, налога на добавленную коррупцию и так далее. Человек, добавляющий данные, может не знать все эти тонкости с налоговой базой, и он определяет чистую цену. С помощью триггера мы можем поправить цену товара на некоторую величину.

Таким образом, триггер будет срабатывать при любой операции INSERT или UPDATE над таблицей Products. Сам триггер будет изменять цену товара, а для получения того товара, который был добавлен или изменен, находим этот товар по Id. Но какое значение должен иметь Id такой товар? Дело в том, что при добавлении или изменении данные сохраняются в промежуточную таблицу inserted. Она создается автоматически. И из нее мы можем получить данные о добавленных/измененных товарах.

И после добавления товара в таблицу Products в реальности товар будет иметь несколько большую цену, чем та, которая была определена при добавлении:

Триггеры в MS SQL Server

Удаление триггера

Для удаления триггера необходимо применить команду DROP TRIGGER :

Отключение триггера

Бывает, что мы хотим приостановить действие триггера, но удалять его полностью не хотим. В этом случае его можно временно отключить с помощью команды DISABLE TRIGGER :

А когда триггер понадобится, его можно включить с помощью команды ENABLE TRIGGER :

ОТКЛЮЧЕНИЕ ТРИГГЕРА

После того как вы создали триггер в Oracle, вам может понадобиться его отключить. Вы можете сделать это с помощью команды ALTER TRIGGER.

Синтаксис

Параметры и аргументы
имя_триггера наименование триггера, который вы хотите отключить.

Примечание

  • Смотрите также, как отключить все триггеры таблицы.
  • Смотрите также, как включить триггер таблицы или включить все триггеры таблицы.

Пример

Рассмотрим пример, который показывает, как отключить триггер в Oracle.

Этот пример использует команду ALTER TRIGGER, для отключения триггера orders_before_insert.

Name already in use

sql-docs / docs / t-sql / statements / disable-trigger-transact-sql.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

DISABLE TRIGGER (Transact-SQL)

Disables a trigger.

. image type=»icon» source=»../../includes/media/topic-link-icon.svg» border=»false». Transact-SQL syntax conventions

schema_name
Is the name of the schema to which the trigger belongs. schema_name cannot be specified for DDL or logon triggers.

trigger_name
Is the name of the trigger to be disabled.

ALL
Indicates that all triggers defined at the scope of the ON clause are disabled.

[!CAUTION]
[!INCLUDEssNoVersion] creates triggers in databases that are published for merge replication. Specifying ALL in published databases disables these triggers, which disrupts replication. Verify that the current database is not published for merge replication before specifying ALL.

object_name
Is the name of the table or view on which the DML trigger trigger_name was created to execute.

DATABASE
For a DDL trigger, indicates that trigger_name was created or modified to execute with database scope.

ALL SERVER
Applies to: [!INCLUDEsql2008-md] and later.

For a DDL trigger, indicates that trigger_name was created or modified to execute with server scope. ALL SERVER also applies to logon triggers.

[!NOTE]
This option is not available in a contained database.

Triggers are enabled by default when they are created. Disabling a trigger does not drop it. The trigger still exists as an object in the current database. However, the trigger does not fire when any [!INCLUDEtsql] statements on which it was programmed are executed. Triggers can be re-enabled by using ENABLE TRIGGER. DML triggers defined on tables can be also be disabled or enabled by using ALTER TABLE.

Changing the trigger by using the ALTER TRIGGER statement enables the trigger.

To disable a DML trigger, at a minimum, a user must have ALTER permission on the table or view on which the trigger was created.

To disable a DDL trigger with server scope (ON ALL SERVER) or a logon trigger, a user must have CONTROL SERVER permission on the server. To disable a DDL trigger with database scope (ON DATABASE), at a minimum, a user must have ALTER ANY DATABASE DDL TRIGGER permission in the current database.

The following examples are described in the AdventureWorks2012 database.

A. Disabling a DML trigger on a table

The following example disables trigger uAddress that was created on table Person .

B. Disabling a DDL trigger

The following example creates a DDL trigger safety with database scope, and then disables it.

C. Disabling all triggers that were defined with the same scope

The following example disables all DDL triggers that were created at the server scope.

SQL Server Disable and Enable Triggers

This chapter of the triggers tutorial will cover a side of triggers that is sometimes overlooked: disabling and re-enabling triggers.

Enabling and Disabling Triggers

Sometimes there are moments where you don’t want a trigger to fire. For example, you may need to load data into an audit table and avoid triggers from firing. The first idea that could come to your mind is to save trigger’s code into a script file and drop it, but there is a more practical solution which is to disable the trigger, do what you need to do and then enable the trigger again.

Disabling SQL Server Triggers

In order to disable any type of SQL Server triggers we use the DISABLE TRIGGER command.

Additionally the next table describes each of the arguments of the DISABLE TRIGGER statement.

Argument Description
Trigger_Name | ALL Trigger_Name: This is the name of the trigger you want to disable. ALL: When this keyword is used instead of a trigger name, then all of the triggers at the scope specified by the ON clause are disabled.
Object_Name | DATABASE | ALL SERVER Object_Name: Only valid for DML triggers. This is the name of the table or views were the trigger belongs. DATABASE: This indicates that the trigger(s) are database scoped. SERVER: This indicates that the trigger(s) are database scoped.

Now let’s disable some triggers in our sample database. In the next script I will disable all triggers in the Person view and the database scoped TR_Schema_Change trigger.

As you may have already noticed, I also added two select statements to the system view sys.triggers so you can see the effect of the DISABLE TRIGGER command by looking at the is_disabled column. In the next image you can see the output of this script.

Disabling triggers.

Additionally we can disable the server scoped trigger we created in the previous chapter. This time, instead of querying sys.triggers we have to query the sys.server_triggers system view.

In the next image you can see the output of the code.

Disabling a server scoped trigger.

Enabling SQL Server Triggers

The statement used to enable any type of SQL Server triggers is the ENABLE TRIGGER command.

Additionally the next table describes each of the arguments of the ENABLE TRIGGER statement.

Argument Description
Trigger_Name | ALL Trigger_Name: This is the name of the trigger you want to enable. ALL: When this keyword is used instead of a trigger name, then all of the triggers at the scope specified by the ON clause are enabled.
Object_Name | DATABASE | ALL SERVER Object_Name: Only valid for DML triggers. This is the name of the table or views were the trigger belongs. DATABASE: This indicates that the trigger(s) are database scoped. SERVER: This indicates that the trigger(s) are database scoped.

In order to show you how to use this command let’s enable the triggers we disabled.

Take a look at the following screen capture to see the output of the code section above.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *