SQL Server 存储过程 循环遍历结果集

这是一个SQL Server的存储过程示例,用于处理任务ID为@tid的任务,并根据@ap的值更新任务的已完成百分比。过程首先检查@ap是否超过100%,如果超过则设为100%。接着,它获取任务的父任务ID,如果存在且不为0,则使用游标遍历所有子任务,累加它们的已完成百分比,并调用自身递归计算剩余部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

USE [Task]
GO
/****** Object:  StoredProcedure [dbo].[pro_name]    Script Date: 09/22/2013 10:35:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[pro_name]
    @tid int,
    @ap float
as
begin
	SET NOCOUNT ON;
	DECLARE @pid int
	DECLARE @AlreadyPercent float
	DECLARE @Percents float
	DECLARE @total float
	if(@ap > 100)
	begin
		set @ap = 100;
	end
	--更新记录
	update tbTask set AlreadyPercent = round(convert(numeric(6,3),@ap),0) where ID = @tid;
	print round(convert(numeric(6,3),@ap),0);
	SET @pid = (select top 1 tbTask.ParentTaskID from tbTask where tbTask.ID=@tid);
	
	--如果记录存在,进入循环
    IF(@pid is not null and @pid != 0)
    BEGIN
		set @total = 0;
    	DECLARE vend_cursor CURSOR
		FOR SELECT tbTask.AlreadyPercent,tbTask.Percents FROM tbTask where tbTask.ParentTaskID = @pid
		OPEN vend_cursor
		FETCH NEXT FROM vend_cursor into @AlreadyPercent,@Percents;
        
        WHILE(@@fetch_status=0)
        BEGIN
			set @total = @total + @AlreadyPercent * @Percents / 100;
            FETCH NEXT FROM vend_cursor into @AlreadyPercent,@Percents;
        END
        --print 'total = ' + cast(@total as varchar);
        close vend_cursor   --关闭游标
        deallocate vend_cursor
        exec pro_name @pid, @total;
    END
end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值