Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

sql - How use inserteddeleted table in stored procedure?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...