This is the sample of cursor solutions, i will add the explanation a bit later
CREATE PROCEDURE AutoSumEventMembers AS SET NOCOUNT ON; /*This stored procedure is used to update the number of players played on the particular event*/ /*Event selected only based on the completed one or the one where the result has been uploaded*/ /*Declare the variable that is used to store the value coming from cursor*/ DECLARE @EventID int DECLARE @TotalResult int /*Declare the cursor for that particular select statement*/ /*You can fetch more that one column into cursor*/ /*You need to make sure that you have the same number of variables when you start fetching it*/ /*Make sure the variable has the same type as the column as well*/ DECLARE Cur_Events CURSOR FOR SELECT EventID FROM Events WHERE Finalised = 1 /*Open the cursor*/ OPEN Cur_Events /*Start fetching from the cursor and dump it into the variable*/ FETCH Cur_Events INTO @EventID /*Iterating through the cursor until the end of the cursor*/ WHILE @@Fetch_Status = 0 BEGIN SET @TotalResult = 0 /*Count how many results have been uploaded for particular event*/ SELECT @TotalResult = COUNT(*) FROM EventResults WHERE EventID = @EventID /*Update the record*/ UPDATE Events SET NumberOfResults = @TotalResult WHERE EventID = @EventID /*Fetch the next cursor*/ FETCH Cur_Events INTO @EventID END /* Clean up - deallocate and close the cursors.*/ CLOSE Cur_Events DEALLOCATE Cur_Events
Leave a Reply