Código SQL:
Ver original
ALTER PROCEDURE sp_c_pago_reemplazo @Total NUMERIC(19,2),@Fecha datetime AS SET nocount ON DECLARE @Pago TABLE (n INT IDENTITY(1,1),pag_id INT,pag_total NUMERIC(19,2)) DECLARE @Resultado TABLE (n INT,pag_id INT,pag_total NUMERIC(19,2)) INSERT @pago SELECT pag_id,pag_total FROM pago WHERE pag_total<=@Total AND YEAR(pag_fecha)=YEAR(@Fecha) AND MONTH(pag_fecha)=MONTH(@Fecha) ORDER BY pag_total DESC,pag_id DESC DECLARE @pag_id INT, @pag_total_idx NUMERIC(19,2), @pag_total NUMERIC(19,2), @pag_total_rep NUMERIC(19,2), @n INT, @l INT, @n_ INT, @l_ INT, @c INT, @r INT, @Suma NUMERIC(19,2) SELECT @n=MIN(n),@l=MAX(n),@Suma=0 FROM @Pago while (@n<=@l) BEGIN -- Limpio tabla de resultados DELETE FROM @Resultado SET @Suma=0 -- Tomo el primer pago SELECT @pag_total_idx=pag_total,@pag_id=pag_id FROM @pago WHERE n=@n IF @pag_total_idx<=@Total INSERT @Resultado SELECT @n,@pag_id,@pag_total_idx -- Verifico si se encontro el total IF @Total=@pag_total_idx GOTO Final ELSE BEGIN SELECT @c=MAX(n), @r=0 FROM @Pago WHERE pag_total<=@Total-@pag_total_idx --print 'Repeticiones '+cast(@c as varchar) while @r<=@c BEGIN -- Repito la busqueda para todas las combinaciones DELETE FROM @Resultado WHERE n<>@n SET @Suma=0 SELECT @n_=MIN(n)+@r, @l_=@l FROM @Pago WHERE pag_total<=@Total-@pag_total_idx AND n>@n while @n_<=@l_ BEGIN SELECT @pag_total=pag_total,@pag_id=pag_id FROM @pago WHERE n=@n_ --print 'Nivel '+cast(@pag_total as varchar) IF (@pag_total_idx+@Suma+@pag_total)<=(@Total) BEGIN INSERT @Resultado SELECT @n_,@pag_id,@pag_total SET @Suma=@Suma+@pag_total END IF (@Suma+@pag_total_idx)=@Total -- Verifico si se encontro el total GOTO Final SET @n_=(SELECT MIN(n) FROM @Pago WHERE n>@n AND n>@n_) END SET @r=@r+1 END END SET @n=(SELECT MIN(n) FROM @pago WHERE n>@n AND pag_total<@pag_total_idx) END DELETE FROM @Resultado Final: SELECT pag_id,pag_total FROM @Resultado ORDER BY n