国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

如何:創建和運行 CLR SQL Server 觸發器

2024-08-31 00:52:57
字體:
來源:轉載
供稿:網友

通過向 SQL Server 項目添加“觸發器”創建 SQL 觸發器。成功部署后,就可以像其他任何 T-SQL 觸發器一樣調用和執行在托管代碼中創建的觸發器。使用托管語言編寫的觸發器可以使用 SqlTriggerContext 類獲得對相關信息的訪問,這些信息與 T-SQL 觸發器的可用信息相同。

注意 
在默認情況下,Microsoft SQL Server 中關閉了公共語言運行庫 (CLR) 集成功能。必須啟用該功能才能使用 SQL Server 項目項。若要啟用 CLR 集成,請使用 sp_configure 存儲過程的“啟用 clr”選項。有關更多信息,請參見 啟用 CLR 集成。
 
注意 
顯示的對話框和菜單命令可能會與幫助中的描述不同,具體取決于您現用的設置或版本。若要更改設置,請在“工具”菜單上選擇“導入和導出設置”。有關更多信息,請參見 Visual Studio 設置。
 

創建 SQL Server 觸發器
創建 SQL Server 觸發器
打開一個現有的“SQL Server 項目”,或者創建一個新項目。有關更多信息,請參見 如何:創建 SQL Server 項目。

從“項目”菜單中選擇“添加新項”。

在 “添加新項”對話框 中選擇“觸發器”。

鍵入新觸發器的“名稱”。

添加觸發器執行時要運行的代碼。請參見下面的第一個示例。

注意 
C++ 示例在編譯時必須使用 /clr:safe 編譯器選項。
 

對于 Visual Basic 和 Visual C#,在“解決方案資源管理器”中,打開“TestScripts”文件夾,再雙擊“Test.sql”文件。

對于 Visual C++,在“解決方案資源管理器”中,雙擊“debug.sql”文件。

將代碼添加到“Test.sql”(Visual C++ 中為“debug.sql”)文件中以執行觸發器。請參見下面的第二個示例。

按 F5 生成、部署并調試此觸發器。有關不進行調試直接部署的信息,請參見 如何:將 SQL Server 項目項部署到 SQL Server 中。

在 “輸出”窗口 中查看結果,然后選擇“從此處顯示輸出:數據庫輸出”。

示例
此示例演示以下這種情況:用戶選擇他們需要的任何用戶名,但是您希望知道哪些用戶輸入了電子郵件地址作為用戶名。此觸發器檢測該信息并將它記錄到審核表。

Visual Basic 復制代碼
Imports System.Data.SqlClient
Imports System.Text.RegularExPRessions
Imports 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 Function
End Class
C# 復制代碼
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++ 復制代碼
#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]+$");
    }
};

向位于項目的 TestScripts 文件夾中的 Test.sql 文件(Visual C++ 中為 debug.sql)添加代碼以執行和測試您的觸發器。例如,如果已部署了觸發器,您可以通過運行腳本對其進行測試,該腳本向設置了此觸發器的表中插入新行,從而可激發此觸發器。以下調試代碼假定存在具有以下定義的兩個表:

CREATE TABLE Users

(

UserName NVARCHAR(200) NOT NULL,

Pass NVARCHAR(200) NOT NULL

)

CREATE TABLE UsersAudit

(

UserName NVARCHAR(200) NOT NULL

)

 復制代碼
-- 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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 兰考县| 南雄市| 阿勒泰市| 华坪县| 米林县| 堆龙德庆县| 天水市| 建昌县| 治县。| 鄯善县| 长白| 吉隆县| 武乡县| 措美县| 彭阳县| 常德市| 安溪县| 禹城市| 象山县| 庆阳市| 桦南县| 阿图什市| 保山市| 西城区| 万盛区| 宜阳县| 改则县| 宾川县| 招远市| 南靖县| 大石桥市| 家居| 松江区| 长武县| 米易县| 海晏县| 和林格尔县| 宜昌市| 滁州市| 云安县| 东方市|