SQL SERVER CLR Trigger功能
生活随笔
收集整理的這篇文章主要介紹了
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 GO4. 可以執行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功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Luogu 1941 飞扬的小鸟
- 下一篇: Redis入门(二)安装和基本操作