Neha Bhatt
Neha Bhatt

Reputation: 67

Create trigger in stored procedure

I am trying to create a trigger inside stored procedure as it will be removed when the table is dropped.

I am getting an error and am not able to execute it.

CREATE PROCEDURE EC5Trigger2
AS
  CREATE TRIGGER trVendorProductsPST
  ON VendorProducts
  FOR INSERT
  AS
  BEGIN
    SET NOCOUNT ON

    DECLARE  @SKU VARCHAR(64)
    SELECT @SKU = I.SKU FROM inserted AS I

    INSERT INTO ProductStockTransactions (SKU, stockingCode)
    VALUES (@SKU, 'A')
  END

  RETURN 0

Upvotes: 4

Views: 8371

Answers (1)

Dale K
Dale K

Reputation: 27448

Here is how you create your trigger inside a stored procedure using dynamic SQL, which is the only way to do it.

CREATE PROCEDURE EC5Trigger2
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @TriggerCode NVARCHAR(max);

  SET @TriggerCode = 'CREATE TRIGGER trVendorProductsPST
    ON VendorProducts
    FOR INSERT
    AS
    BEGIN
      SET NOCOUNT ON
      DECLARE @SKU VARCHAR(64)
      SELECT @SKU = I.SKU from INSERTED as I

      INSERT INTO ProductStockTransactions (SKU, stockingCode)
        VALUES (@SKU, ''A'')
    END';

  EXEC(@TriggerCode);

  RETURN 0;
END;

Upvotes: 8

Related Questions