孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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的引用

posted on 2012-12-06 21:11  孤独的猫  阅读(839)  评论(0编辑  收藏  举报