在另一个插入中使用来自触发器的 INSERT 信息

Use INSERT information from trigger in another insert

我正在编写一个触发器 after insert,它使用插入的数据将数据插入另一个 table。 这部分,我想通了 但是,我想使用新插入的数据,插入 another table.

CREATE TRIGGER [dbo].[tr_Subsite_Insert]
   ON  [dbo].[Subsite]
   AFTER INSERT
AS 
BEGIN


    INSERT INTO TranslationKey
        SELECT 'base.' + inserted.[name] + '.' + sst.name FROM SubsiteText sst
            CROSS JOIN inserted

    --Use the result of the above INSERT to insert in another table.
    --Example code below:
    INSERT INTO Translation
       SELECT lng.id, inserted2.id, '' FROM Languages lng
       CROSS JOIN inserted2
    --Obviously, "inserted2" doesn't exist.

END
GO

如何从第一个插入中获取值,以便在第二个插入中使用它们?

这里有 2 个选项:

  1. TranslationKey table 上创建另一个触发器(这很简单)
  2. 使用OUTPUT关键字(我会详细说明)

声明一个table变量并使用OUTPUT关键字来获取新插入的IDs。然后在 CROSS JOIN 中使用该温度 table。这是一个例子:

/*here you should change UNIQUEIDENTIFIER to 
  actual type of ID column in TranslationKey table*/
DECLARE @t TABLE ( ID UNIQUEIDENTIFIER )

INSERT  INTO TranslationKey
OUTPUT  INSERTED.ID
        INTO @t
        SELECT  'base.' + inserted.[name] + '.' + sst.name
        FROM    SubsiteText sst
                CROSS JOIN inserted

INSERT  INTO Translation
        SELECT  lng.id ,
                t.ID ,
                ''
        FROM    Languages lng
                CROSS JOIN @t t