触发器不更新sql
尽管此操作在完成时已成功完成,但并未具有所需的更新。
CREATE TRIGGER Trigger1 On dbo.[table1] FOR UPDATE AS Declare @Id int; SELECT @Id = Issue_Id FROM dbo.[table1] INSERT INTO dbo.[storage] SELECT Id, Title, project, Problem FROM dbo.[table2] WHERE Id = @Id
我做错了什么或者我不能在触发器范围内使用变量吗?
非常感谢
Although this is completed successfully on completion, it is not having the desired update.
CREATE TRIGGER Trigger1 On dbo.[table1] FOR UPDATE AS Declare @Id int; SELECT @Id = Issue_Id FROM dbo.[table1] INSERT INTO dbo.[storage] SELECT Id, Title, project, Problem FROM dbo.[table2] WHERE Id = @Id
Is there something I am doing wrong or that I can't use variables within the scope of a trigger?
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
支持多行更新
如果 table2 实际上是 table1 (这更有意义:
table1
与storage
和table2
有何关系?)...To support multirow updates
If table2 is actually table1 (which makes more sense: how is
table1
related tostorage
andtable2
?)...要一次性处理多个更新和
inserted
表:To handle multple updates and the
inserted
table in one go:请仔细阅读以下建议。
而不是下面的行,
它必须是下面的。
以下是更新后的内容。
有关详细信息
在 SQL Server 中,正在插入/修改或删除的记录占用 DML 触发器中可用的两个临时表中。这些表被插入和删除。 INSERTED 表已插入或更新记录。 DELETED 表具有正在更新或删除的记录的旧状态。
Please go through the below suggestion.
Instead of the below line
It had to be following.
Following is the updated one.
For more information
In SQL server the records which are being inserted / modified or deleted occupies themselves in two temporary tables available in a DML trigger. These tables are INSERTED and DELETED. The INSERTED table has inserted or updated records. The DELETED table has the old state of the records being updated or deleted.
其他人已经正确回答,您应该使用
inserted
和联接来构建正确的触发器。但是:根据您对其他人答案的评论 - 您永远不应该尝试从触发器访问您自己的数据库之外的任何资源,更不用说从另一台服务器访问。
尝试将触发器活动与跨服务器活动解耦 - 假设您的触发器将一行添加到队列表中(或使用真正的服务代理队列),并让一个独立的组件负责为这些请求提供服务。
否则,如果存在任何网络问题,不仅您的触发器会中断,而且还会强制回滚原始更新 - 它会使您的本地数据库无法使用。
这也意味着独立组件可以应对超时,并执行适当的重试等。
The others have correctly answered that you should be using
inserted
and a join, to build a proper trigger. But:Based on your comments to other's answers - you should never attempt to access any resource outside of your own database from a trigger, let along from another server.
Try to decouple the trigger activity from the cross server activity - say have your trigger add a row to a queue table (or use real service broker queues), and have an independent component be responsible for servicing these requests.
Otherwise, if there are any e.g. network issues, not only does your trigger break, but it forces a rollback for the original update also - it makes your local database unusable.
This also means that the independent component can cope with timeouts, and perform appropriate retries, etc.
应删除下面的行
SELECT @Id = Issue_Id FROM dbo.[table1]
它应该如下。
从插入的内容中选择 Issue_Id
below line should be removed
SELECT @Id = Issue_Id FROM dbo.[table1]
It should be following.
SELECT Issue_Id FROM Inserted