Stored-Procedures

從觸發器執行儲存過程

  • January 24, 2018

AFTER INSERT我在執行儲存過程的表上設置了觸發器。由於某種原因,在表上發生插入後,儲存過程不會執行並阻止插入。

當我嘗試從新的 T-SQL 執行儲存過程時,它工作得很好。

我嘗試將 try catch 添加到觸發器,但沒有擷取到錯誤。

我嘗試使用 SQL Server Profiler 進行故障排除,發現儲存過程在插入後開始執行,但在中間停止,儘管它說語句已完成。

有什麼想法可能導致這種情況,以及如何解決?

您需要發布觸發器和儲存過程的程式碼以及表定義,以獲得最佳幫助。我能夠將這個對我有用的快速範例放在一起。

當您執行 try/catch 時,我假設您正在將擷取記錄到某處的表中?

/** Cleanup **/
IF OBJECT_ID('Temp1') IS NOT NULL
   DROP TABLE Temp1;

IF OBJECT_ID('Temp2') IS NOT NULL
   DROP TABLE Temp2;

IF OBJECT_ID('TempTest') IS NOT NULL
   DROP PROCEDURE TempTest;
GO

/** Create our objects **/
CREATE TABLE Temp1 (ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY, TextValue VARCHAR(100) NULL);

CREATE TABLE Temp2
   (
       ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
       , Temp1ID INT NULL
       , TextValue VARCHAR(100) NULL
   );
GO

CREATE PROCEDURE TempTest (@ID AS INT)
AS
BEGIN
   INSERT INTO Temp2 (Temp1ID, TextValue)
   SELECT ID
          , TextValue
   FROM Temp1
   WHERE ID = @ID;

END;
GO

CREATE TRIGGER trgTemp1After
ON Temp1
AFTER INSERT
AS
DECLARE @ID INT;

DECLARE curTest CURSOR READ_ONLY LOCAL STATIC FORWARD_ONLY FOR
   SELECT ID
   FROM INSERTED;

OPEN curTest;

FETCH NEXT FROM curTest
INTO @ID;

WHILE @@FETCH_STATUS = 0
BEGIN
   EXEC TempTest @ID;

   FETCH NEXT FROM curTest
   INTO @ID;
END;

CLOSE curTest;
DEALLOCATE curTest;
GO

/** Insert into Temp1
   Ideally, we should see the same entry appear in Temp2
   **/
INSERT INTO Temp1 (TextValue)
VALUES ('This is a test');

SELECT ID
      , TextValue
FROM Temp1;

SELECT ID
      , Temp1ID
      , TextValue
FROM Temp2;

引用自:https://dba.stackexchange.com/questions/196083