Simple academic project. Simple procedure. If there is something already in Payments table – then take debt value from that table, if there are no values – take it from Tariff table. But why such conidtion doesn’t work?
ALTER PROCEDURE dbo.GetDebt
(
@LoanId int
)
AS
IF NOT EXISTS (SELECT top 1 * FROM Payment WHERE LoanId = @LoanId)
BEGIN
SELECT (TotalLoan + ( ( TotalLoan / 100 ) * Interest)) as Debt FROM Loan L, Tariff T
WHERE L.TariffIf = L.TariffId
END
ELSE
BEGIN
SELECT MIN(Debt) as Debt FROM Loan L
RIGHT OUTER JOIN Payment P -- Joins are cool.
ON L.LoanId = P.LoanId
WHERE P.LoanId = @LoanId
END
If/Else is almost always the entirely wrong approach for sql code. It’s hard to give you an exact example without knowing more about your tables, but you really want something more like this:
No If/Else required.