0

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
2
  • You forgot to add ON clause in right join. Commented Dec 19, 2012 at 22:40
  • 3
    Also, you forgot to never use right join. Commented Dec 19, 2012 at 22:40

2 Answers 2

4

use BEGIN and END around your statements like so:

IF (SELECT count(*) FROM Payment WHERE LoanId = @LoanId) = 0 
BEGIN

    SELECT (TotalLoan + ( ( TotalLoan / 100 ) * Interest))  as Debt FROM Loan L 
    RIGHT OUTER JOIN Tariff -- TODO: Add correct ON clause here
    WHERE L.LoanId = @LoanId

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

Also note that you are missing an on clause for your right outer joins which will cause errors.

Also it might be more efficient to change

IF (SELECT count(*) FROM Payment WHERE LoanId = @LoanId) = 0 

to

IF NOT EXISTS (SELECT * FROM Payment WHERE LoanId = @LoanId)

The keyword being "might"

Sign up to request clarification or add additional context in comments.

3 Comments

This isn't working. I tried this, before posting this question. Still error at WHERE.
Dude, I copied your sql without really looking it at. Your sql is not working to begin with because you are missing the on and its expressions after your right outer join
Oh... That's sad that I didn't notice this.
3

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:

SELECT COALESCE(P.Debt, TotalLoan + ( ( TotalLoan / 100 ) * Interest))  as Debt
FROM Loan L
LEFT JOIN Tariff T ON T.LoanID = L.LoanID
LEFT JOIN (SELECT LoanID, Min(Debt) As Debt FROM Payment GROUP BY LoanID) P
WHERE L.LoanID = @LoanID

No If/Else required.

1 Comment

As for description of COALESCE, I'll analyze how it works and will use it. Looking better, then IF..ELSE statements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.