C#SQL SERVER 2008のトリガを追加

3771 ワード

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がYesの場合、日付が変更された年が2012でない場合は、エラーが報告されます.
また、Systemを使用することに注意する.Transactions.Transaction.Current.Rollback()は、Systemを追加する必要があります.Transactionsの参照