SqlTriggerContext Класс

Определение

Предоставляет контекстную информацию о сработавшем триггере.

public ref class SqlTriggerContext sealed
public sealed class SqlTriggerContext
type SqlTriggerContext = class
Public NotInheritable Class SqlTriggerContext
Наследование
SqlTriggerContext

Примеры

В следующем примере показан объект , используемый SqlTriggerContext для определения того, Insert произошло ли действие. Если строка была вставлена в таблицу user, имя пользователя и реальное имя извлекаются из вставленной строки, а затем добавляются в таблицу UserNameAudit .

[SqlTrigger(Name = @"UsersAudit", Target = "[dbo].[users]", Event = "FOR INSERT")]
public static void UsersAudit()
{
   // Get the trigger context.
   string userName;
   string realName;
   SqlCommand command;
   SqlTriggerContext triggContext = SqlContext.TriggerContext;
   SqlDataReader reader;

   switch (triggContext.TriggerAction)
   {
      case TriggerAction.Insert:

      // Retrieve the connection that the trigger is using.
      using (SqlConnection connection
         = new SqlConnection(@"context connection=true"))
      {
         connection.Open();

         // Get the inserted row.
         command = new SqlCommand(@"SELECT * FROM INSERTED;",
                                  connection);

         // Get the user name and real name of the inserted user.
         reader = command.ExecuteReader();
         reader.Read();
         userName = (string)reader[0];
         realName = (string)reader[1];
         reader.Close();

         // Insert the user name and real name into the auditing table.
         command = new SqlCommand(@"INSERT [dbo].[UserNameAudit] (userName, realName) "
                  + @"VALUES (@userName, @realName);", connection);

         command.Parameters.Add(new SqlParameter("@userName", userName));
         command.Parameters.Add(new SqlParameter("@realName", realName));

         command.ExecuteNonQuery();
      }

      break;
   }
}
<SqlTrigger(Name:="UsersAudit", Target:="[dbo].[users]", Event:="FOR INSERT")> _
Public Shared Sub UsersAudit()
        
   Dim command As SqlCommand
   Dim triggContext As SqlTriggerContext
   Dim reader As SqlDataReader
   Dim userName As String
   Dim realName As String

         
   ' Get the trigger context.
   triggContext = SqlContext.TriggerContext        

   Select Case triggContext.TriggerAction
           
      Case TriggerAction.Insert

         ' Retrieve the connection that the trigger is using.
         Using connection As New SqlConnection("context connection=true")
            connection.Open()

            ' Get the inserted row.
            command = new SqlCommand("SELECT * FROM INSERTED;", connection)
            
            ' Get the user name and real name of the inserted user.                
            reader = command.ExecuteReader()
            reader.Read()
            userName = CType(reader(0), String)
            realName = CType(reader(1), String)

            reader.Close()

            ' Insert the user name and real name into the auditing table.
            command = New SqlCommand("INSERT [dbo].[UserNameAudit] (userName, realName) " & _
               "VALUES (@userName, @realName);", connection)

            command.Parameters.Add(new SqlParameter("@userName", userName))
            command.Parameters.Add(new SqlParameter("@realName", realName))
                 
            command.ExecuteNonQuery()
                 
          End Using
         
   End Select

End Sub

Комментарии

Предоставляемые контекстные сведения включают тип действия, вызвавшего срабатывание триггера, столбцы, которые были изменены в операции UPDATE, а в случае триггера языка определения данных (DDL) — структуру XML EventData (см . справочник по Transact-SQL), описывающую операцию активации.

Экземпляр SqlTriggerContext доступен из SqlContext класса , когда код выполняется внутри триггера через TriggerContext свойство .

Свойства

ColumnCount

Получает число столбцов, содержащихся в таблице данных, привязанной к триггеру. Это свойство доступно только для чтения.

EventData

Получает данные о событии, связанном с действием, которое вызвало срабатывание триггера.

TriggerAction

Показывает, какое действие вызвало срабатывание триггера.

Методы

IsUpdatedColumn(Int32)

Возвращает true, если столбец был обработан оператором INSERT или UPDATE.

Применяется к