zoukankan      html  css  js  c++  java
  • C#添加SQL SERVER 2008的触发器

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

  • 相关阅读:
    Ajax原生请求及Json基础
    HTML5拖拽练习
    表格单元格间数据的拖拽
    query 获取本身的HTML
    JQuery UI的拖拽功能实现方法小结
    ASP.NET MVC4中使用bootstrip模态框时弹不出的问题
    窗口中各模块的切换效果,使用jquery实现
    窗口模块自适应高度
    新jQuery中attr 与 prop的不同
    用js+css3做一个小球投篮的动画(easing)
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2806169.html
Copyright © 2011-2022 走看看