0

简单的学术项目。简单的程序。如果 Payments 表中已经存在某些内容 - 然后从该表中获取债务值,如果没有值 - 从 Tariff 表中获取它。但是为什么这样的条件不起作用呢?

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
4

2 回答 2

3

像这样使用BEGINEND围绕你的陈述:

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

另请注意,您缺少一个会导致错误的on子句。right outer joins

也可能更有效地改变

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

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

关键词是“可能”

于 2012-12-19T22:33:34.247 回答
3

If/Else 几乎总是对 sql 代码完全错误的方法。如果不了解更多有关您的表的信息,很难给您一个确切的示例,但您确实想要更像这样的东西:

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

不需要 If/Else。

于 2012-12-19T22:46:34.757 回答