12

I creating triggers for several tables. The triggers have same logic. I will want to use a common stored procedure. But I don't know how work with inserted and deleted table.

example:

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
1
  • 2
    You can't. the pseudo-tables are only available directly in triggers. And your code is broken. inserted can contain 0, 1, or multiple rows - SET @FiledId = (SELECT FiledId FROM inserted) is selecting a value from one of those rows and ignoring the others Commented Jan 22, 2014 at 8:32

3 Answers 3

10

You can use a table valued parameter to store the inserted / deleted values from triggers, and pass it across to the proc. e.g., if all you need in your proc is the UNIQUE FileID'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

And then pass the inserted / deleted ids from the trigger, e.g.:

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Once you have the Type and proc in place, its 3 LOC per trigger, which you say you already have ?
My 2 cents: Beware that triggers can be hard to debug and putting too much logic in them is bound to get you into trouble down the road.
6

You can

select * into #Inserted from inserted
select * into #Deleted from deleted

and then

use these two temp tables in your stored proc

Comments

0

The tables inserted and deleted are only available inside the trigger. You can only use them in run-time. They will then contain the affected rows.

Also, your code might not work as expected if there is not exactly one row inserted.

2 Comments

Maybe Can I pass the table in a parameter ?
Sorry, not to a trigger. But perhaps you cold use dynamic sql to do what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.