在数据库的日常操作中,面对复杂业务的情况下,总会有用sql语句或存储过程不是那么方便的时候,所以这时候就会想到在数据库中调用CLR,也就是调用程序集,此处用C#实现来讲解一个测试案例

  测试案例的业务是:我有两张表分别命名为A,B,当我在A表中插入一条数据时,这时我希望将插入的记录中的某些字段插入到B表中。很明显,很快我们会想到触发器,其实这个业务并不复杂,我们在一个触发器中就可以轻松实现,但是基于此篇博文的目的,我把向B表插入数据的功能放到了程序集里面,也就是我们的C#程序中。废话不多说,我们接下来就开始

     1.建表,A,B。表结构如下(A,B表表结构一样,均是下面的Error表)

      SQL触发器与CLR的使用

      2.然后我们开始建程序集了,就是我们的动态库 

    
 1 using Microsoft.SqlServer.Server;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data.SqlClient;
 5 using System.Text;
 6 using System.Data;
 7 using System.Threading;
 8 
 9 namespace TestProc
10 {
11     public class TestClass
12     {
13         [Microsoft.SqlServer.Server.SqlTrigger(Name = "ELMAH_Error_Trigger", Target = "ELMAH_Error", Event = "FOR INSERT ")]
14         public static void triggerInsert()
15         {
16             string id = "";
17             DateTime dt = DateTime.Now;
18             //获取插入A表的数据
19             using (SqlConnection cn = new SqlConnection())
20             {
21                 cn.ConnectionString = "context connection=true";
22                 cn.Open();
23 
24                 using (SqlCommand cmd = cn.CreateCommand())
25                 {
26                     cmd.CommandText = "select a.Name, a.Tctime from INSERTED a";
27                     SqlDataReader dr = cmd.ExecuteReader();
28                     StringBuilder sb = new StringBuilder();
29                     while (dr.Read())
30                     {
31                         id = dr[0].ToString();
32                         dt=Convert.ToDateTime(dr[1]);
33                         SqlContext.Pipe.Send(id+dt.ToShortDateString()+"\r\n");
34                     }
35                 }
36             }
37             
38             using (SqlConnection cn1 = new SqlConnection())
39             {
40                 cn1.ConnectionString =@"server =192.168.0.102\DATAUM; database =HR;user id = sa ;password =123456";
41                 cn1.Open();
42                 using (SqlCommand cmd1 = cn1.CreateCommand())
43                 {
44                     cmd1.CommandText = "insert into Error Values(" + id + ",'" + dt + "')";
45                     SqlContext.Pipe.Send(cmd1.CommandText + "\r\n");
46                     cmd1.ExecuteNonQuery();
47                 }
48             }
49         }
50     }
51 }
View Code

分类:

技术点:

相关文章: