日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

SQL SERVER CLR Trigger功能

發布時間:2024/7/5 数据库 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SQL SERVER CLR Trigger功能 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

通過在 Microsoft SQL Server 中托管 CLR(稱為 CLR 集成),開發人員可以在托管代碼中編寫存儲過程、觸發器、用戶定義函數、用戶定義類型和用戶定義聚合函數, 改變了以前只能通過T-SQL語言來實現這些功能的局面。因為托管代碼在執行之前會編譯為本機代碼,所以,在有些方案中可以大大提高性能。

?

1. 編寫C#代碼,編譯成.NET 3.5的dll

public class Program {[SqlTrigger(Name = @"UsersAudit", Target = "[dbo].[users]", Event = "FOR INSERT")]public static void UsersAudit(){SqlContext.Pipe.Send("UsersAudit start");// 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;}SqlContext.Pipe.Send("UsersAudit end");}[Microsoft.SqlServer.Server.SqlProcedure]public static void HelloWorld(out string text){SqlContext.Pipe.Send("Hello world!" + Environment.NewLine);text = "Hello world!";} }

  

2. SMSS中選擇“可編程性” -> "程序集"->“右鍵”-》“新建程序集”,將編譯的dll注冊

3.打開SMSS查詢窗口,執行一下的sql語句將觸發器和存儲過程注冊。注意程序集名稱和命名空間名稱的格式。

CREATE PROCEDURE hello @i nchar(25) OUTPUT AS EXTERNAL NAME SqlTriggerContextTest.Program.HelloWorld GO -- if the HelloWorldProc class is inside a namespace (called MyNS), -- the last line in the create procedure statement would be -- EXTERNAL NAME helloworld.[MyNS.HelloWorldProc].HelloWorld CREATE TRIGGER UsersAudit ON [dbo].[users] AFTER INSERT, UPDATE AS EXTERNAL NAME SqlTriggerContextTest.Program.UsersAudit GO

4. 可以執行sql語句查看效果 

?

運行 select * from sys.assemblies? 可以查看注冊的程序集

如果dll中需要使用TCP功能,那么程序集必須簽名。

?

參考:https://www.cnblogs.com/alexcodinglife/articles/5563148.html

?

轉載于:https://www.cnblogs.com/Martianhh/p/10826857.html

總結

以上是生活随笔為你收集整理的SQL SERVER CLR Trigger功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。