如何:創(chuàng)建和運(yùn)行 CLR SQL Server 觸發(fā)器
通過(guò)向 SQL Server 項(xiàng)目添加“觸發(fā)器”創(chuàng)建 SQL 觸發(fā)器。成功部署后,就可以像其他任何 T-SQL 觸發(fā)器一樣調(diào)用和執(zhí)行在托管代碼中創(chuàng)建的觸發(fā)器。使用托管語(yǔ)言編寫(xiě)的觸發(fā)器可以使用 SqlTriggerContext 類獲得對(duì)相關(guān)信息的訪問(wèn),這些信息與 T-SQL 觸發(fā)器的可用信息相同。
注意; 在默認(rèn)情況下,Microsoft SQL Server 中關(guān)閉了公共語(yǔ)言運(yùn)行庫(kù) (CLR) 集成功能。必須啟用該功能才能使用 SQL Server 項(xiàng)目項(xiàng)。若要啟用 CLR 集成,請(qǐng)使用 sp_configure 存儲(chǔ)過(guò)程的“啟用 clr”選項(xiàng)。有關(guān)更多信息,請(qǐng)參見(jiàn) 啟用 CLR 集成。注意; 顯示的對(duì)話框和菜單命令可能會(huì)與幫助中的描述不同,具體取決于您現(xiàn)用的設(shè)置或版本。若要更改設(shè)置,請(qǐng)?jiān)凇肮ぞ摺辈藛紊线x擇“導(dǎo)入和導(dǎo)出設(shè)置”。有關(guān)更多信息,請(qǐng)參見(jiàn) Visual Studio 設(shè)置。
創(chuàng)建 SQL Server 觸發(fā)器創(chuàng)建 SQL Server 觸發(fā)器打開(kāi)一個(gè)現(xiàn)有的“SQL Server 項(xiàng)目”,或者創(chuàng)建一個(gè)新項(xiàng)目。有關(guān)更多信息,請(qǐng)參見(jiàn) 如何:創(chuàng)建 SQL Server 項(xiàng)目。
從“項(xiàng)目”菜單中選擇“添加新項(xiàng)”。
在 “添加新項(xiàng)”對(duì)話框 中選擇“觸發(fā)器”。
鍵入新觸發(fā)器的“名稱”。
添加觸發(fā)器執(zhí)行時(shí)要運(yùn)行的代碼。請(qǐng)參見(jiàn)下面的第一個(gè)示例。
注意; C++ 示例在編譯時(shí)必須使用 /clr:safe 編譯器選項(xiàng)。
對(duì)于 Visual Basic 和 Visual C#,在“解決方案資源管理器”中,打開(kāi)“TestScripts”文件夾,再雙擊“Test.sql”文件。
對(duì)于 Visual C++,在“解決方案資源管理器”中,雙擊“debug.sql”文件。
將代碼添加到“Test.sql”(Visual C++ 中為“debug.sql”)文件中以執(zhí)行觸發(fā)器。請(qǐng)參見(jiàn)下面的第二個(gè)示例。
按 F5 生成、部署并調(diào)試此觸發(fā)器。有關(guān)不進(jìn)行調(diào)試直接部署的信息,請(qǐng)參見(jiàn) 如何:將 SQL Server 項(xiàng)目項(xiàng)部署到 SQL Server 中。
在 “輸出”窗口 中查看結(jié)果,然后選擇“從此處顯示輸出:數(shù)據(jù)庫(kù)輸出”。
示例此示例演示以下這種情況:用戶選擇他們需要的任何用戶名,但是您希望知道哪些用戶輸入了電子郵件地址作為用戶名。此觸發(fā)器檢測(cè)該信息并將它記錄到審核表。
Visual Basic 復(fù)制代碼Imports System.Data.SqlClientImports System.Text.RegularExpressionsImports Microsoft.SqlServer.Server
Partial Public Class Triggers
<SqlTrigger(Name:='UserNameAudit', Target:='Users', Event:='FOR INSERT')> _ Public Shared Sub UserNameAudit()
Dim triggContext As SqlTriggerContext = SqlContext.TriggerContext() Dim userName As New SqlParameter('@username', SqlDbType.NVarChar)
If triggContext.TriggerAction = TriggerAction.Insert Then
Using conn As New SqlConnection('context connection=true')
conn.Open() Dim sqlComm As New SqlCommand Dim sqlP As SqlPipe = SqlContext.Pipe()
sqlComm.Connection = conn sqlComm.CommandText = 'SELECT UserName from INSERTED'
userName.Value = sqlComm.ExecuteScalar.ToString()
If IsEMailAddress(userName.ToString) Then sqlComm.CommandText = 'INSERT UsersAudit(UserName) VALUES(username)' sqlP.Send(sqlComm.CommandText) sqlP.ExecuteAndSend(sqlComm) End If End Using End If End Sub
Public Shared Function IsEMailAddress(ByVal s As String) As Boolean
Return Regex.IsMatch(s, '^([w-]+.)*?[w-]+@[w-]+.([w-]+.)*?[w]+$') End FunctionEnd ClassC# 復(fù)制代碼using System.Data.SqlClient;using System.Text.RegularExpressions;using Microsoft.SqlServer.Server;
public partial class Triggers{ [SqlTrigger(Name='UserNameAudit', Target='Users', Event='FOR INSERT')] public static void UserNameAudit() { SqlTriggerContext triggContext = SqlContext.TriggerContext; SqlParameter userName = new SqlParameter('@username', System.Data.SqlDbType.NVarChar);
if (triggContext.TriggerAction == TriggerAction.Insert) { using (SqlConnection conn = new SqlConnection('context connection=true')) { conn.Open(); SqlCommand sqlComm = new SqlCommand(); SqlPipe sqlP = SqlContext.Pipe;
sqlComm.Connection = conn; sqlComm.CommandText = 'SELECT UserName from INSERTED';
userName.Value = sqlComm.ExecuteScalar().ToString();
if (IsEMailAddress(userName.ToString())) { sqlComm.CommandText = 'INSERT UsersAudit(UserName) VALUES(userName)'; sqlP.Send(sqlComm.CommandText); sqlP.ExecuteAndSend(sqlComm); } } } }
public static bool IsEMailAddress(string s) { return Regex.IsMatch(s, '^([w-]+.)*?[w-]+@[w-]+.([w-]+.)*?[w]+$'); }}C++ 復(fù)制代碼#include 'stdafx.h'
#using <System.dll>#using <System.Data.dll>#using <System.Xml.dll>
using namespace System;using namespace System::Data;using namespace System::Data::Sql;using namespace System::Data::SqlClient;using namespace System::Data::SqlTypes;using namespace System::Text::RegularExpressions;using namespace Microsoft::SqlServer::Server;
// In order to debug your Trigger, add the following to your debug.sql file://// -- Insert one user name that is not an e-mail address and one that is// INSERT INTO Users(UserName, Pass) VALUES(N'someone', N'cnffjbeq')// INSERT INTO Users(UserName, Pass) VALUES(N'someone@example.com', N'cnffjbeq')//// -- check the Users and UsersAudit tables to see the results of the trigger// SELECT * FROM Users// SELECT * FROM UsersAudit//
public ref class AddNewTrigger{public: [SqlTrigger(Name='UserNameAudit', Target='Users', Event='FOR INSERT')] static void UserNameAudit() { SqlTriggerContext ^triggContext = SqlContext::TriggerContext; SqlParameter ^userName = gcnew SqlParameter('@username', System::Data::SqlDbType::NVarChar);
if (triggContext->TriggerAction == TriggerAction::Insert) { SqlConnection ^conn = gcnew SqlConnection('context connection=true'); conn->Open(); SqlCommand ^sqlComm = gcnew SqlCommand(); SqlPipe ^sqlP = SqlContext::Pipe;
sqlComm->Connection = conn; sqlComm->CommandText = 'SELECT UserName from INSERTED';
userName->Value = sqlComm->ExecuteScalar()->ToString();
if (IsEMailAddress(userName->ToString())) { sqlComm->CommandText = 'INSERT UsersAudit(UserName) VALUES(userName)'; sqlP->Send(sqlComm->CommandText); sqlP->ExecuteAndSend(sqlComm); }
conn->Close(); } }
static bool IsEMailAddress(String ^s) { return Regex::IsMatch(s, '^([w-]+.)*?[w-]+@[w-]+.([w-]+.)*?[w]+$'); }};
向位于項(xiàng)目的 TestScripts 文件夾中的 Test.sql 文件(Visual C++ 中為 debug.sql)添加代碼以執(zhí)行和測(cè)試您的觸發(fā)器。例如,如果已部署了觸發(fā)器,您可以通過(guò)運(yùn)行腳本對(duì)其進(jìn)行測(cè)試,該腳本向設(shè)置了此觸發(fā)器的表中插入新行,從而可激發(fā)此觸發(fā)器。以下調(diào)試代碼假定存在具有以下定義的兩個(gè)表:
CREATE TABLE Users
(
UserName NVARCHAR(200) NOT NULL,
Pass NVARCHAR(200) NOT NULL
)
CREATE TABLE UsersAudit
(
UserName NVARCHAR(200) NOT NULL
)
復(fù)制代碼-- Insert one user name that is not an e-mail address and one that isINSERT INTO Users(UserName, Pass) VALUES(N'someone', N'cnffjbeq')INSERT INTO Users(UserName, Pass) VALUES(N'someone@example.com', N'cnffjbeq')
-- check the Users and UsersAudit tables to see the results of the triggerselect * from Usersselect * from UsersAudit
