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

  • 相关阅读:
    spring-data-jpa 二、多对一结构、Repository
    bootstrap学习(二)页面
    bootstrap学习(一)栅格、布局
    ArrayList源码学习
    python学习-Pillow图像处理
    python学习-抓取知乎图片
    python-os创建文件夹-create_dir_if_not_exist.py
    python-shutil学习
    python-argparse批量修改后缀名-batch_file_rename.py
    python-argparse使用
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2806169.html
Copyright © 2011-2022 走看看