对于.net来讲触发器也是方法,在上方标注[Microsoft.SqlServer.Server.SqlTrigger]标签(只我这样翻译)。
我们看一个小例子
右键部署using System; using System.Data; using System.Data.Sql; using Microsoft.SqlServer.Server; using System.Data.SqlClient; public partial class Triggers ...{ //Name触发器的名字 //Target触发器对应表 //Event可以是FOR INSERT、FOR DELETE和FOR UPDATE [Microsoft.SqlServer.Server.SqlTrigger(Name = "NameInfoTrigger", Target = "NameInfo", Event = "FOR UPDATE")] public static void ReturnDifferenceCs() ...{ using (SqlConnection cn = new SqlConnection()) ...{ cn.ConnectionString = "context connection=true"; cn.Open(); using (SqlCommand cmd = cn.CreateCommand()) ...{ cmd.CommandText = "insert into ChangeHistory select b.name + '->' + a.name,getdate() from INSERTED a JOIN DELETED b ON a.id = b.id"; SqlContext.Pipe.ExecuteAndSend(cmd); } } } }
数据库里的两张表
我执行两条UPDATE语句
update [NameInfo] set [name]='David' where id=1
update [nameinfo] set [name]='Fan' where id=2
结果update [nameinfo] set [name]='Fan' where id=2
再执行两条
update [NameInfo] set [name]='*David*' where id=1
update [nameinfo] set [name]='*Fan*' where id=2
再看结果update [nameinfo] set [name]='*Fan*' where id=2