Here is some code for an sql stored procedure for looping through a result set of rows and then executing some code foreach row.
ALTER PROCEDURE [dbo].[DeleteMilestone]
-- Add the parameters for the stored procedure here
@ApplicationId uniqueidentifier,
@MilestoneId uniqueidentifier
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @rowcount int --Declared to number of records
DECLARE @ProjectId uniqueidentifier
DECLARE @TaskId uniqueidentifier
DECLARE @OrderNum int
-- get the ProjectId
SELECT @ProjectId=ProjectId FROM Milestones WHERE ApplicationId=@ApplicationId AND MilestoneId=@MilestoneId
-- get the number of MilestoneTasks that are open (open Tasks' OrderNum will not be 0)
SELECT @rowcount=COUNT(TaskId) FROM MilestoneTasks WHERE MilestoneId=@MilestoneId AND OrderNum<>0
WHILE @rowcount > 0
BEGIN
-- select tasks that are still open (open Tasks' OrderNum will not be 0)
-- selecting the top 1 should give me the highest order milestone task
SELECT TOP 1 @TaskId=TaskId FROM MilestoneTasks WHERE MilestoneId=@MilestoneId AND OrderNum<>0 ORDER BY OrderNum
-- select max ordernum <>0 from ProjectTasks
SELECT @OrderNum=MAX(OrderNum)+1 FROM ProjectTasks WHERE ProjectId=@ProjectId AND OrderNum<>0
-- update the OrderNum of this Task in ProjectTasks
UPDATE ProjectTasks SET OrderNum=@OrderNum WHERE ProjectId=@ProjectId AND TaskId=@TaskId
-- update the OrderNum of this Task to 0 in MilestoneTasks
UPDATE MilestoneTasks SET OrderNum=0 WHERE MilestoneId=@MilestoneId AND TaskId=@TaskId
-- update the number of MilestoneTasks that are open (open Tasks' OrderNum will not be 0)
SELECT @rowcount=COUNT(TaskId) FROM MilestoneTasks WHERE MilestoneId=@MilestoneId AND OrderNum<>0
END
DELETE FROM Milestones WHERE ApplicationId=@ApplicationId AND MilestoneId=@MilestoneId
END
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.