现在的位置: 首页 > 综合 > 正文

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

2013年12月07日 ⁄ 综合 ⁄ 共 979字 ⁄ 字号 评论关闭
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

抱歉!评论已关闭.