I would like to monitor a table for inserts and call a stored procedure with the value which has been inserted.
Monitored Table (BatchDetails) will have the following columns BatchID,BatchStartTime,BatchEndTime
Stored Procedure will use the latest BatchID which has been inserted
Note: There will always be only one row inserted at a time.
I have been looking at this link but seem that there is lot going on ie, several tables. Is there a simple way of doing this?
You can user a trigger like this:
CREATE TRIGGER TR_Monitor_BatchDetails_Inserts
ON BatchDetails
AFTER INSERT
AS
BEGIN
DECLARE @BatchId INT
SELECT TOP 1 @BatchId = BatchId
FROM INSERTED
ORDER BY [PK_ColumnHere/Date/OtherOrderingColumn] DESC
EXEC SomeStoredProc @BatchId
END
But there are a few flaws with it:
1 - there CAN be more rows in INSERTED
(rows that are being inserted) and this wont handle all of them
2 - you may want to call your procedure from where the inserts are being made into BatchDetails
table. Maybe have a proc that does the inserts, and add there the call to this your procedure. That will be a better way to approach this.
Hope it makes sense
Elaborating a bit on previous answer and considering more than 1 inserted row you could try something like this:
CREATE TRIGGER TR_Monitor_BatchDetails_Inserts
ON BatchDetails
AFTER INSERT
AS
BEGIN
DECLARE @BatchId INT
Declare bcursor cursor local for
SELECT BatchId FROM INSERTED ORDER BY [PK_ColumnHere/Date/OtherOrderingColumn] DESC
open bcursor
fetch next from bcursor into @BatchId
while @@FETCH_STATUS = 0 begin
EXEC SomeStoredProc @BatchId
fetch next from bcursor into @BatchId
end
close bcursor
deallocate bcursor
END
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.