使用clr触发器转换sql触发器

时间:2016-04-10 11:38:24

标签: c# sql-server triggers clr sqlclr

我是CLR的新手,我想用clr触发器转换在sql server中创建的触发器,而不是在学习clr的过程中。

这是SMO中触发器的当前代码:

CREATE TRIGGER tr_tblAircraft_ForInsert
ON tblAircraft
FOR INSERT
AS 
BEGIN
    Declare @ID int
    Select @ID=AircraftID from inserted
    Declare @NrOfAircraft int
    Select @NrOfAircraft=AircraftUnits from inserted

    Insert into tblAircraftOrderAudit
    values('New aircraft order for ' + Cast(@NrOfAircraft as nvarchar(5)) + ' aircraft with ID = ' + Cast(@ID as nvarchar(5)) + ' was added at ' + Cast(GetDate() as nvarchar(20)))
    END

这是我的clr代码到底有多远:

using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public partial class Triggers
{        
    // Enter existing table or view for the target and uncomment the attribute line
    [SqlTrigger(Name="SqlTriggerAircraftOrderAudit", Target="tblAircraft", Event="FOR INSERT, UPDATE")]
    public static void SqlTriggerAircraftOrderAudit ()
    {
        Int32 ID;
        Int32 NrOfAircraft;
        SqlCommand command;
        SqlTriggerContext triggContext = SqlContext.TriggerContext;
        SqlPipe pipe = SqlContext.Pipe;
        SqlDataReader reader;

        using (SqlConnection connection
            = new SqlConnection(@"context connection=true"))
        {
            connection.Open();
            command = new SqlCommand(@"SELECT * FROM INSERTED;",
               connection);
            reader = command.ExecuteReader();
        reader.Read();
        ID = (Int32)reader[0];
        NrOfAircraft = (Int32)reader[1];
        reader.Close();

        SqlContext.Pipe.Send("Trigger FIRED");
    }
}
}

由于

0 个答案:

没有答案