I have been asked to create a trigger which realizes an update of the balance field of the loan table, which is calculated by adding all the payments made in the column amount in the payment tablePrestamos, so I must do an update of all the Loans and your balance to pay the tables have these characteristics:
create table prestamo(
idCuenta int identity(1,1),
cantidadCuotas int not null,
monto decimal(13,2) not null,
saldo decimal(13,2) not null,
constraint pk_idprestamo primary key(idCuenta)
);
insert into prestamo values(60, 500000, 500000),(60, 5000000, 5000000), (60, 600000, 600000),(60, 1000000, 500000)
create table pagoPrestamo(
idPago int identity(1,1),
idCuenta int not null,
monto decimal(13,2) not null,
fecha date not null,
constraint pk_idpago primary key(idPago),
constraint fk_idcuent foreign key (idCuenta) references prestamo(idCuenta)
);
insert into pagoPrestamo values(2,5000,'03/03/2018'),(4,10000,'04/13/2018'),(6,15000,'02/23/2018'),(8,45000,'04/04/2018'),(1,50000,'06/05/2018')
The trigger I created is this:
create trigger tr_pago_prestamo on pagoPrestamo
after insert
as
Begin
declare @idPrestamo int
declare @prestamoMonto decimal(13,2)
declare @pagoMonto decimal(13,2)
declare @saldo decimal(13,2)
select @pagoMonto = Sum(monto) from pagoPrestamo where pagoPrestamo.idCuenta = @idPrestamo
select @prestamoMonto = monto from prestamo where idCuenta = @idPrestamo
select @saldo = @prestamoMonto - @pagoMonto
declare logica cursor for select prestamo.idCuenta, prestamo.monto, prestamo.saldo from prestamo inner join pagoPrestamo on prestamo.idCuenta = pagoPrestamo.idCuenta
open logica
while (@@FETCH_STATUS = 0 )
begin
update prestamo set prestamo.saldo = prestamo.monto - @pagoMonto
fetch next from logica into @idPrestamo, @prestamoMonto, @saldo
end
close logica
deallocate logica
end
The problem is when I execute the trigger, it puts the account's balance in null and I do not know why. I am new to using the cursor, thank you very much for your help