在插入触发器期间更新数据然后插入

时间:2013-05-21 09:57:50

标签: sql-server triggers

我有情况,我在表中有10列。我从一个程序插入5列,对于5列,我想创建一个触发器。可能吗?如果是的话,我该怎么做?

col1 col2 col3 col4 col5 col6 col7 col8 col9 col10

CREATE TRIGGER Fill_Trigger
   ON  DB 
   AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    DECLARE @COL6 INT
    DECLARE @COL7 INT -- and so on.


   SET @COL6 = (SELECT COL1 FROM inserted) * (SELECT COL2 FROM inserted)
   SET @COL7 = (SELECT COL3 FROM inserted) * (SELECT COL4 FROM inserted)

   --Is it possible to do the following?
  UPDATE inserted SET COL6 = @COL6
  UPDATE inserted SET COL7 = @COL7
END
GO

1 个答案:

答案 0 :(得分:1)

你不应该在触发器中使用locsal变量,因为它使它成为“仅单行”

另外,我假设您有一个名为KeyColumn的主键。您的表名为“DB”。

CREATE TRIGGER Fill_Trigger
   ON DB 
   AFTER INSERT
AS 
BEGIN
   SET NOCOUNT ON;

   UPDATE DB
   SET
       Col6 = I.COL1 * COL2,
       Col7 = I.COL3 * COL4
   FROM
       DB
       JOIN
       INSERTED I ON DB.KeyColumn = I.KeyColumn;
END
GO

但是,有些列基于其他列,我会使用COMPUTED columns而没有触发器

CREATE TABLE MyTable (
    KeyColumn ...,
    Col1 ...,
    Col2 ...,
    Col3 ...,
    Col4 ...,
    Col5 ...,

    Col6 AS Col1 * Col2,
    Col7 AS Col3 * Col4,
    Col8 AS ...

    );