现在的位置: 首页 > 综合 > 正文

C#添加SQL SERVER 2008的触发器

2011年12月04日 ⁄ 综合 ⁄ 共 1098字 ⁄ 字号 评论关闭

C#可以为SQL SERVER 2008添加触发器,步骤为

在C#中,选择"新建项目"->"数据库"->"SQL Server"->"Visual C# SQL CLR 数据库"

在项目中,单击右键选择"添加"->"触发器",代码如下(ValidateYear.cs):

 1 using System;
 2 using System.Data;
 3 using System.Data.SqlClient;
 4 using Microsoft.SqlServer.Server;
 5 
 6 
 7 public partial class Triggers
 8 {
 9     // 为目标输入现有表或视图并取消对特性行的注释
10     [Microsoft.SqlServer.Server.SqlTrigger (Name="ValidateYear", 
11         Target="HumanResources", Event="FOR INSERT")]
12     public static void ValidateYear()
13     {
14         // 用您的代码替换
15         SqlConnection conn = new SqlConnection("Context connection=true");
16 
17         //定义查询
18         string sql =
19             "SELECT COUNT(*) " +
20             "FROM INSERTED " +
21             "WHERE YEAR(ModifiedDate)<>2012";
22 
23         SqlCommand comm = new SqlCommand(sql, conn);
24 
25         //打开连接
26         conn.Open();
27         //获得行数
28         int numBadRows = (int)comm.ExecuteScalar();
29 
30         if (numBadRows > 0)
31         {
32             //Get the SqlPipe
33             SqlPipe pipe = SqlContext.Pipe;
34             //role back and raise an error
35             comm.CommandText = "RAISEERROR('修改错误',11,1)";
36 
37             //send the error
38             try
39             {
40             }
41             catch
42             {
43             }
44             System.Transactions.Transaction.Current.Rollback();
45         }
46         conn.Close();
47     }
48 }

用于验证插入的数据是否合法,当插入表HumanResources是,如果修改日期的年份不是2012将报错。

另外要注意的是要使用System.Transactions.Transaction.Current.Rollback(),必须添加System.Transactions的引用

抱歉!评论已关闭.