本文介绍了SQL Server-插入触发器后-更新同一表中的另一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此数据库触发器:

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.

推荐答案

这取决于数据库上当前设置的触发器的递归级别。

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).

还是,我认为这是个好主意。更好的选择是使用。这样,您将避免在数据库上执行第一次(手动)更新。

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-插入触发器后-更新同一表中的另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:26