简体   繁体   English

触发更新 SQL 服务器表

[英]Trigger on Update on SQL Server table

I would like to update one Column value for certain condition for a SQL Server table.我想为 SQL 服务器表的特定条件更新一个列值。 I have the following code for creation of table我有以下用于创建表的代码

CREATE TABLE [dbo].[EQUIPMENT](
 [ID] [int] IDENTITY(10000,1) NOT NULL,
 [Equipment] [nvarchar](80) NOT NULL,
 [Facility] [nvarchar](40) NULL,
 [EquipmentType] [smallint] NULL,
 [Active] [bit] NOT NULL)

Following are the Insert and Update Statements以下是插入和更新语句

INSERT INTO [Equipment] ([Equipment],[Facility],[EquipmentType],[Active]) VALUES ('E02','1029',10,1)
UPDATE [Equipment] Set Active = 0 where [Equipment] = 'E01'

Following is the Trigger script以下是触发脚本

CREATE TRIGGER dbo.ATRG_EquipmentTypeUpdate
ON [dbo].[Equipment]
AFTER INSERT, UPDATE
AS 
BEGIN   
   SET NOCOUNT ON;

   -- update your table, using a set-based approach
   -- from the "Inserted" pseudo table which CAN and WILL
   -- contain multiple rows!
   UPDATE [dbo].[Equipment] 
   SET  EquipmentType  = 15 
   FROM Inserted i
   WHERE [dbo].[Equipment].ID = i.ID
   AND [dbo].[Equipment].EquipmentType = 10
END
GO

As I try to Run the Insert OR update statement - I have the following error.当我尝试运行 Insert OR update 语句时 - 我有以下错误。

Msg 217, Level 16, State 1, Procedure ATRG_EquipmentTypeUpdate1, Line 12 [Batch Start Line 9]
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

Can any body advise?任何机构都可以提供建议吗? There are three other triggers in the table.表中还有其他三个触发器。 This, I need as a temporary solution, for workaround.这个,我需要作为临时解决方案,用于解决方法。

A trigger that updates its table won't fire again unless you opt-in to Recursive Triggers , so check the RECURSIVE TRIGGERS database setting, and if it's on, turn it off:除非您选择加入Recursive Triggers ,否则更新其表的触发器不会再次触发,因此请检查 RECURSIVE TRIGGERS 数据库设置,如果已打开,请将其关闭:

alter database current set recursive_triggers off

Or code your trigger to not perform an UPDATE of zero rows, eg或者将您的触发器编码为不执行零行的更新,例如

if not exists (select * from inserted) return

You can use TRIGGER_NESTLEVEL to check for recursive calls.您可以使用TRIGGER_NESTLEVEL检查递归调用。

You should also check for no rows in inserted .您还应该检查inserted的行中是否没有行。

CREATE TRIGGER dbo.ATRG_EquipmentTypeUpdate
ON [dbo].[Equipment]
AFTER INSERT, UPDATE
AS 
BEGIN
   SET NOCOUNT ON;

   IF TRIGGER_NESTLEVEL(OBJECT_ID('dbo.ATRG_EquipmentTypeUpdate', 'AFTER', 'DML')) > 1
      OR NOT EXISTS (SELECT 1 FROM inserted)
       RETURN;

   -- update your table, using a set-based approach
   -- from the "Inserted" pseudo table which CAN and WILL
   -- contain multiple rows!
   UPDATE 
   SET EquipmentType = 15 
   FROM Inserted i
   JOIN [dbo].[Equipment] e ON e.ID = i.ID
     AND e.EquipmentType = 10;
END

Note also the use of proper JOIN syntax in the update.还要注意在更新中使用正确的JOIN语法。

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

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