我该如何使用触发器?
我有一个包含一些表的数据库,
每当表中写入一些数据时,我想在 C# 中运行一个方法。
我知道我必须使用触发器,但我不知道如何!!!
如果您指导我,我将不胜感激。
PS:
我正在使用 SQLExpress 2008
I have a Database with some tables,
I wanna to run a method in C# whenever some data is written in the tables.
I know I have to use triggers, but I don't know how!!!
It would be appreciated if you guide me.
P.S:
I'm using SQLExpress 2008
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ADO.NET 提供了非常有用的类,称为 SqlDependency。当数据库中的指定表发生更改时,您可以订阅
OnChange
事件。以下是文档和示例:
http://msdn.microsoft.com/en- us/library/62xk7953.aspx
它看起来非常漂亮并且有效!
但是,您必须在数据库中启用 Service Broker 才能接收这些通知。以下是如何做到这一点:
ADO.NET provides very useful class called SqlDependency. You can subsribe to an
OnChange
event when specified table in database changes.Here is documentation and example:
http://msdn.microsoft.com/en-us/library/62xk7953.aspx
It looks very nice and works!
However, you will have to enable Service Broker in your database in order to receive these notification. Here is how to do that:
我认为一种方法是创建一个用 C# 编写的函数或存储过程。例如,这在 SQL Server 和 DB2 中是可能的。
然后您的触发器将能够调用此 SQL Server 函数/SP。
但老实说,对我来说这并不是一个好的设计。
I think one way to do that would be to create a function or a stored procedure written in C#. This is possible in SQL Server and DB2 for example.
Then your trigger would be able to call this SQL Server function/SP.
But honestly, it does not look like a good design to me.
有一些选项可以在数据库中运行 .NET 代码,但就个人而言?我不会。我希望我的数据库负责存储和获取数据,仅此而已。选项:
还要考虑数据库的事务性质 - 可能即使您完成插入/更新后,事务永远不会提交(请注意,使用第一种方法,如果正确完成,对第二个表的插入也会同时自动回滚)
There are some options to run .NET code in the database, but personally? I wouldn't. I want my database to worry about storing and fetching data, that is all. Options:
Also consider the transactional nature of the database - it might be that even though you've done an INSERT/UPDATE, the transaction never gets committed (note that with the first approach, the insert to the second table will also be automatically rolled back at the same time, if done correctly)