-
Create a new SQL Server project in Visual Studio and name it ClrDdlTrigger.
-
Create a trigger item in the project. Name the item LogTableActivityTrigger.cs.
using System;
using System.Data;using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
public partial class Triggers
{public static void LogTableActivityTrigger()
{
SqlTriggerContext tc = SqlContext.TriggerContext;
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
if (tc.TriggerAction == TriggerAction.CreateTable ||
tc.TriggerAction == TriggerAction.DropTable)
{
cmd.CommandText = "INSERT INTO Log VALUES " +
"('" + tc.EventData.Value + "')";
cmd.ExecuteNonQuery();
}
}
}
}
1<EVENT_INSTANCE>
<EventType>CREATE_TABLE</EventType>
<PostTime>2007-11-03T17:25:45.407</PostTime>
<SPID>52</SPID>
<ServerName>CTSUSNJY9779A</ServerName>
<LoginName>CTSUSNJY9779A\bill</LoginName>
<UserName>dbo</UserName>
<DatabaseName>AdoDotNet35Cookbook</DatabaseName>
| <SchemaName>dbo</SchemaName>
<ObjectName>TestTable</ObjectName>
<ObjectType>TABLE</ObjectType>
<TSQLCommand>
<SetOptions
ANSI_NULLS="ON"
ANSI_NULL_DEFAULT="ON"
ANSI_PADDING="ON"
QUOTED_IDENTIFIER="ON"
ENCRYPTED="FALSE"
/>
<CommandText>
CREATE
TABLE TestTable
(
TestID int NOT NULL,
CONSTRAINT PK_TestTable PRIMARY KEY CLUSTERED
( TestID ASC )
)
</CommandText>
</TSQLCommand>
</EVENT_INSTANCE>
2
<EVENT_INSTANCE>
<EventType>DROP_TABLE</EventType>
<PostTime>2007-11-03T17:25:45.827</PostTime>
<SPID>52</SPID>
<ServerName>CTSUSNJY9779A</ServerName>
<LoginName>CTSUSNJY9779A\bill</LoginName>
<UserName>dbo</UserName>
<DatabaseName>AdoDotNet35Cookbook</DatabaseName>
<SchemaName>dbo</SchemaName>
<ObjectName>TestTable</ObjectName>
<ObjectType>TABLE</ObjectType>
<TSQLCommand>
<SetOptions
ANSI_NULLS="ON"
ANSI_NULL_DEFAULT="ON"
ANSI_PADDING="ON"
QUOTED_IDENTIFIER="ON"
ENCRYPTED="FALSE"
/>
<CommandText>DROP
TABLE TestTable</CommandText>
</TSQLCommand>
</EVENT_INSTANCE>

Join the conversation! Your thoughts help the community grow.