如何使用IF ... ELSE sql语句有多个选择?

时间:2012-12-19 22:31:41

标签: sql tsql

简单的学术项目。简单的程序。如果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

2 个答案:

答案 0 :(得分: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)

关键字为“可能”

答案 1 :(得分:3)

如果/ 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

否如果/需要。