如何在存储过程中使用插入/删除表?

问题描述

您可以使用表值参数存储触发器中插入/删除的值,并将其传递给proc。例如,如果您在proc中所需的全部是UNIQUEFileID's

CREATE TYPE FileIds AS TABLE
(
    FileId INT
);

-- Create the proc to use the type as a TVP
CREATE PROC commonProc(@FileIds AS FileIds READONLY)
    AS
    BEGIN
        UPDATE at
            SET at.DateVersion = CURRENT_TIMESTAMP
        FROM ATable at
            JOIN @FileIds fi
            ON at.FileID = fi.FileID;
    END

然后从触发器中传递插入/删除的ID,例如:

CREATE TRIGGER MyTrigger ON SoMetable FOR INSERT
AS
    BEGIN
        DECLARE @FileIds FileIDs;
        INSERT INTO @FileIds(FileID)
            SELECT disTINCT FileID FROM INSERTED;
        EXEC commonProc @FileIds;
    END;

解决方法

我为几个表创建触发器。触发器具有相同的逻辑。我将要使用一个通用的存储过程。但是我不知道如何处理 插入删除的 表。

例子:

SET @FiledId = (SELECT FiledId FROM inserted)
begin tran
   update table with (serializable) set DateVersion = GETDATE()
   where FiledId = @FiledId

   if @@rowcount = 0
   begin
      insert table (FiledId) values (@FiledId)
   end
commit tran