use telekom
go

create procedure sp_tuzba
(
	@idKorisnika int,
	@maksDozvoljenDug decimal(10,2)
)
as
begin
	declare @dug decimal(10,2)
	
	select @dug = sum(r.iznos)
	from racuni r left join tuzbe t
	on r.idKorisnika = t.idKorisnika
	where r.idKorisnika = @idKorisnika
	and r.datumUplate is null
	and t.id is null

	if @dug > @maksDozvoljenDug
	begin
		insert into tuzbe(idKorisnika, datumTuzbe)
		values(@idKorisnika, GETDATE())
	end
end
