问题描述
我有这个数据库触发器:
I've got this database trigger:
CREATE TRIGGER setDescToUpper
ON part_numbers
AFTER INSERT,UPDATE
AS
DECLARE @PnumPkid int, @PDesc nvarchar(128)
SET @PnumPkid = (SELECT pnum_pkid FROM inserted)
SET @PDesc = (SELECT UPPER(part_description) FROM inserted)
UPDATE part_numbers set part_description_upper = @PDesc WHERE pnum_pkid=@PnumPkid
GO
这是个坏主意吗? 即更新同一个表中的列.我希望它为插入和更新触发.
Is this a bad idea? That is to update a column on the same table. I want it to fire for both insert and update.
它有效,我只是害怕周期性情况.触发器内部的更新会一次又一次地触发触发器.这会发生吗?
It works, I'm just afraid of a cyclical situation. The update, inside the trigger, fires the trigger, and again and again. Will that happen?
请不要挑剔大写的东西.疯狂的情况.
Please, don't nitpick at the upper case thing. Crazy situation.
推荐答案
这取决于当前在 DB 上设置的触发器的递归级别.
It depends on the recursion level for triggers currently set on the DB.
如果你这样做:
SP_CONFIGURE 'nested_triggers',0
GO
RECONFIGURE
GO
或者这个:
ALTER DATABASE db_name
SET RECURSIVE_TRIGGERS OFF
不会再次调用上面的触发器,这样您就很安全了(除非您陷入某种僵局;那是可能的,但也许我错了).
That trigger above won't be called again, and you would be safe (unless you get into some kind of deadlock; that could be possible but maybe I'm wrong).
不过,我不认为这是个好主意.更好的选择是使用 INSTEAD OF 触发器.这样您就可以避免对数据库执行第一次(手动)更新.只会执行触发器中定义的那个.
Still, I do not think this is a good idea. A better option would be using an INSTEAD OF trigger. That way you would avoid executing the first (manual) update over the DB. Only the one defined inside the trigger would be executed.
INSTEAD OF INSERT 触发器如下所示:
An INSTEAD OF INSERT trigger would be like this:
CREATE TRIGGER setDescToUpper ON part_numbers
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO part_numbers (
colA,
colB,
part_description
) SELECT
colA,
colB,
UPPER(part_description)
) FROM
INSERTED
END
GO
这会自动替换"原来的 INSERT 语句,并将显式 UPPER 调用应用于 part_description
字段.
This would automagically "replace" the original INSERT statement by this one, with an explicit UPPER call applied to the part_description
field.
INSTEAD OF UPDATE 触发器类似(我不建议您创建单个触发器,将它们分开).
An INSTEAD OF UPDATE trigger would be similar (and I don't advise you to create a single trigger, keep them separated).
此外,这解决了@Martin 评论:它适用于多行插入/更新(您的示例没有).
Also, this addresses @Martin comment: it works for multirow inserts/updates (your example does not).
这篇关于SQL Server - 插入触发器后 - 更新同一表中的另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!