我该如何使用触发器?

发布于 2024-09-18 04:42:22 字数 147 浏览 2 评论 0原文

我有一个包含一些表的数据库,
每当表中写入一些数据时,我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

乜一 2024-09-25 04:42:22

ADO.NET 提供了非常有用的类,称为 SqlDependency。当数据库中的指定表发生更改时,您可以订阅 OnChange 事件。

以下是文档和示例:

http://msdn.microsoft.com/en- us/library/62xk7953.aspx

它看起来非常漂亮并且有效!

void Initialization()
{
    // Create a dependency connection.
    SqlDependency.Start(connectionString, queueName);
}

void SomeMethod()
{
    // Assume connection is an open SqlConnection.

    // Create a new SqlCommand object.
    using (SqlCommand command=new SqlCommand(
        "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers", 
        connection))
    {

        // Create a dependency and associate it with the SqlCommand.
        SqlDependency dependency=new SqlDependency(command);
        // Maintain the refence in a class member.

        // Subscribe to the SqlDependency event.
        dependency.OnChange+=new
           OnChangeEventHandler(OnDependencyChange);

        // Execute the command.
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Process the DataReader.
        }
    }
}

// Handler method
void OnDependencyChange(object sender, 
   SqlNotificationEventArgs e )
{
  // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    // Release the dependency.
    SqlDependency.Stop(connectionString, queueName);
}

但是,您必须在数据库中启用 Service Broker 才能接收这些通知。以下是如何做到这一点:

--Create login if you do not have already
--Example:
--CREATE LOGIN ChangesMonitor WITH PASSWORD = 'ChangesMonitor' ;
--GO

--Create user associated with this login and
--add provilages in Management Studio tab Security->Users
--(not sure if all are needed, but for test purposes add following):
--db_datareader, db_datawriter,  db_ddladmin, db_accesadmin, db_owner, db_securityadmin



--must have exclusiveness on database
--script for database SqlDependExample and for user ChangesMonitor
ALTER DATABASE SqlDependExample SET ENABLE_BROKER
GO

GRANT CREATE PROCEDURE TO [ChangesMonitor];
GO
GRANT CREATE SERVICE TO [ChangesMonitor];
GO

GRANT CREATE QUEUE TO [ChangesMonitor];
GO

GRANT REFERENCES ON CONTRACT::[http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification] TO [ChangesMonitor];
GO
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO [ChangesMonitor];
GO

GRANT CONTROL ON SCHEMA::[dbo] TO [ChangesMonitor];
GO

GRANT IMPERSONATE ON USER::DBO TO [ChangesMonitor];
GO 

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!

void Initialization()
{
    // Create a dependency connection.
    SqlDependency.Start(connectionString, queueName);
}

void SomeMethod()
{
    // Assume connection is an open SqlConnection.

    // Create a new SqlCommand object.
    using (SqlCommand command=new SqlCommand(
        "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers", 
        connection))
    {

        // Create a dependency and associate it with the SqlCommand.
        SqlDependency dependency=new SqlDependency(command);
        // Maintain the refence in a class member.

        // Subscribe to the SqlDependency event.
        dependency.OnChange+=new
           OnChangeEventHandler(OnDependencyChange);

        // Execute the command.
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Process the DataReader.
        }
    }
}

// Handler method
void OnDependencyChange(object sender, 
   SqlNotificationEventArgs e )
{
  // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    // Release the dependency.
    SqlDependency.Stop(connectionString, queueName);
}

However, you will have to enable Service Broker in your database in order to receive these notification. Here is how to do that:

--Create login if you do not have already
--Example:
--CREATE LOGIN ChangesMonitor WITH PASSWORD = 'ChangesMonitor' ;
--GO

--Create user associated with this login and
--add provilages in Management Studio tab Security->Users
--(not sure if all are needed, but for test purposes add following):
--db_datareader, db_datawriter,  db_ddladmin, db_accesadmin, db_owner, db_securityadmin



--must have exclusiveness on database
--script for database SqlDependExample and for user ChangesMonitor
ALTER DATABASE SqlDependExample SET ENABLE_BROKER
GO

GRANT CREATE PROCEDURE TO [ChangesMonitor];
GO
GRANT CREATE SERVICE TO [ChangesMonitor];
GO

GRANT CREATE QUEUE TO [ChangesMonitor];
GO

GRANT REFERENCES ON CONTRACT::[http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification] TO [ChangesMonitor];
GO
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO [ChangesMonitor];
GO

GRANT CONTROL ON SCHEMA::[dbo] TO [ChangesMonitor];
GO

GRANT IMPERSONATE ON USER::DBO TO [ChangesMonitor];
GO 
夜访吸血鬼 2024-09-25 04:42:22

我认为一种方法是创建一个用 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.

鲜血染红嫁衣 2024-09-25 04:42:22

有一些选项可以在数据库中运行 .NET 代码,但就个人而言?我不会。我希望我的数据库负责存储和获取数据,仅此而已。选项:

  • 使用触发器(或任何其他方法)填充事件队列,即另一个表;让您的 C# 应用程序轮询此表以了解需要执行的操作
  • 在您的应用程序层中编写代码(即,在执行数据更改命令时运行代码)

还要考虑数据库的事务性质 - 可能即使您完成插入/更新后,事务永远不会提交(请注意,使用第一种方法,如果正确完成,对第二个表的插入也会同时自动回滚)

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:

  • use a trigger (or any other approach) to populate an event queue, i.e. another table; have your C# app poll this table for things to do
  • write the code in your app tier instead (i.e. run the code as part of making the data-change command)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文