简体   繁体   English

SQL Server更新触发器

[英]SQL Server Update Trigger

I have never used triggers before in SQL server and I have looked around online but haven't found an answer to my question. 我之前从未在SQL服务器中使用过触发器,而且我已经在网上查看但是没有找到我的问题的答案。 Basically I am trying to write an Trigger that will run after a record has been updated in a table. 基本上我正在尝试编写一个触发器,它将在表中更新记录后运行。 This trigger will then update two additional tables based on the record that was updated in the first table. 然后,此触发器将根据第一个表中更新的记录更新另外两个表。

The primary table with the trigger on it will be updating one record using a query like this: 带有触发器的主表将使用如下查询更新一条记录:

UPDATE E.SM_T_RList
SET IsActive = 0
WHERE Guid = @Guid

I then want the trigger to do something like this: 然后我想让触发器做这样的事情:

ALTER TRIGGER [E].[IsActiveUpdate] 
ON  [E].[SM_T_RList] 
AFTER UPDATE
AS
BEGIN

SET NOCOUNT ON;

UPDATE E.SM_T_BInfo
SET IsActive = 0
WHERE Guid = @Guid

UPDATE E.SM_T_RMachines
SET IsActive = 0
WHERE GUID = @GUID

END

The Guid that I want updated is being used by the primary table. 我希望更新的Guid正在被主表使用。 But I can't figure out how I get the @Guid that I want updated into the trigger? 但我无法弄清楚如何将我希望更新的@Guid更新到触发器中? Please help. 请帮忙。

Thanks 谢谢

Both the answers already posted suffer from the same problem - they're marking the other rows as Inactive, whenever any update occurs on your base table 已发布的答案都存在同样的问题 - 只要基表上发生任何更新,它们就会将其他行标记为非活动状态

Something like: 就像是:

ALTER TRIGGER [E].[IsActiveUpdate] 
ON  [E].[SM_T_RList] 
AFTER UPDATE
AS
BEGIN

SET NOCOUNT ON;

UPDATE E.SM_T_BInfo
SET IsActive = 0
WHERE Guid IN (SELECT Guid FROM INSERTED where IsActive=0)

UPDATE E.SM_T_RMachines
SET IsActive = 0
WHERE Guid IN (SELECT Guid FROM INSERTED where IsActive=0)

END

Would be more appropriate 会更合适

Triggers in SQL Server operate on sets of rows not individual rows. SQL Server中的触发器对行集而不是单个行进行操作。 You access these via the inserted and deleted pseudo tables. 您可以通过inserteddeleted伪表访问它们。 Assuming that you might want the value of isactive to cascade when previously inactive rows were made active you could use something like this. 假设您可能希望在先前非活动行处于活动状态时将isactive的值级联,您可以使用类似这样的内容。

ALTER TRIGGER [E].[IsActiveUpdate] 
ON  [E].[SM_T_RList] 
AFTER UPDATE
AS
BEGIN

SET NOCOUNT ON;

UPDATE E.SM_T_BInfo
SET IsActive = i.IsActive
FROM INSERTED i JOIN E.SM_T_BInfo e
ON e.Guid = i.Guid

UPDATE E.SM_T_RMachines
SET IsActive = i.IsActive
FROM INSERTED i JOIN E.SM_T_BInfo e
ON e.Guid = i.Guid

END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM