使用参数在sql server的触发器中执行存储过程

时间:2017-01-31 17:34:42

标签: sql sql-server stored-procedures triggers insert

我创建了一个触发器,它将在INSERT上执行存储过程:

telnet

我想要实现的是使用参数执行存储过程,这些参数表示刚刚插入的行,并且基本上触发了此触发器。

2 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,这是我的解决方法。

USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 ALTER TRIGGER [dbo].[trigger_name] ON [dbo].[table_name]
  AFTER INSERT AS
  BEGIN
    SET NOCOUNT ON
    DECLARE @nRows INT;
    DECLARE @var1 DATETIME;
    DECLARE @InsertedDates TABLE (
        NewDate DATETIME
    );

    INSERT INTO @InsertedDates
    SELECT [column name]
    FROM INSERTED;

    SELECT @nRows = COUNT(*) FROM @InsertedDates;

    WHILE @nRows > 0
    BEGIN
        SELECT TOP 1 @var1 = NewDate FROM @InsertedDates;

        EXEC    procedure_name_exec @var1;

        DELETE FROM @InsertedDates 
        WHERE @var1 = NewDate;

        SELECT @nRows = COUNT(*) FROM @InsertedDates;
    END;
  END;

总体思路是认识到 Inserted 是一个表,您需要处理每一行。为此,我制作了表的副本(不确定是否有必要)并处理表变量,然后从表变量中删除我处理的行。

注意:如果处理插入的重复很重要,那么您需要对它们进行计数并多次调用存储过程。

答案 1 :(得分:-2)

以下是寻找的内容,并给了我正在寻找的结果:

USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 ALTER TRIGGER [dbo].[trigger_name] ON [dbo].[table_name]
  AFTER INSERT AS
  BEGIN
    SET NOCOUNT ON
    declare @var1 DATETIME
    SELECT @var1 = inserted.[column name] 
    FROM inserted

    EXEC procedure_name_exec @var1
  END