4

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
10
  • why you wanna create a trigger more than once? I assume that since you made it in a procedure Commented Apr 25, 2019 at 22:14
  • 1
    your trigger is broken anyway and wont work as intended for multirow inserts. you should get rid of the assignment to the scalar variable and just insert straight from inserted to the target table Commented Apr 25, 2019 at 22:18
  • 1
    Why aren't you solving the basic problem : I am trying to save trigger in SP as it will be removed when the table is dropped. the simplest solution is to save the create trigger in file. After you re-create the table, just execute the create trigger script
    – Squirrel
    Commented Apr 26, 2019 at 2:21
  • 1
    Your trigger has MAJOR flaw in that you seem to assume it'll be called once per row - that is not the case. The trigger will fire once per statement, so if your INSERT that causes this trigger to fire inserts 25 rows, you'll get the trigger fired once and the Inserted pseudo table will contain 25 rows. Which of those 25 rows will your code select from Inserted? It's non-deterministic, you'll get one arbitrary row and you will be ignoring all other rows. You need to rewrite your trigger to take this into account!
    – marc_s
    Commented Apr 26, 2019 at 4:08
  • 1
    NO - neither a cursor, nor a while loop - use a proper, set-based approach - that's the most efficient by far
    – marc_s
    Commented Apr 26, 2019 at 20:26

1 Answer 1

8

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;
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.