如果在SQL Server存储过程中ELSE

时间:2016-05-31 02:37:55

标签: sql sql-server if-statement stored-procedures

我正在尝试在SQL Server存储过程中完成IF ELSE语句,但似乎它不会遵循这个条件。我试图为我声明一个静态值来检查它,但它仍然是相同的。我的问题是即使条件错误也不会去ELSE

以下是代码:

ALTER PROCEDURE [dbo].[Amount_Computation]
    (@OfficeID int,
     @AccountID int,
     @Amount int,
     @NoOfMonths int,
     @Percentage int,
     @isRoundOf int,
     @MaxAmount int,
     @EmployeeType int)
AS
    declare @TotalAmount table(TotalAmount int)
    declare @Casual table(CasualSalary int, OfficeID int)
    declare @Regular table(RegularSalary int, OfficeID int)

    declare @basic int
BEGIN
    SELECT 
        @Amount = 1, @OfficeID = 72,
        @AccountID = 733, @Amount = 0, 
        @NoOfMonths = 12, @Percentage = 1.25, 
        @isRoundOf = 1, @MaxAmount = 35000, 
        @EmployeeType = 1

    IF(@Amount = 0)
    BEGIN
         INSERT INTO @Casual 
             SELECT 
                 CAST(((select LEFT(CONVERT(nvarchar,CAST((Case when (basic * 22 > @MaxAmount) then @MaxAmount ELSE Basic * 22 END) AS INT)),LEN(CONVERT(nvarchar,CAST((Case when (basic * 22 > @MaxAmount) then @MaxAmount ELSE Basic * 22 END) AS INT))) - 3)) + '000' ) AS INT ) * @Percentage / 100 * @NoOfMonths as Casual, 
                 a.OfficeID 
             FROM 
                 pmis.dbo.vw_RGPermanentAndCasual as a 
             LEFT JOIN 
                 ifmis.dbo.tbl_R_BMSOffices as b ON b.PMISOfficeID = a.OfficeID 
             WHERE 
                 a.OfficeID = @OfficeID AND a.EmploymentGroup = '2'

        INSERT INTO @Regular 
            SELECT 
                CAST(((select LEFT(CONVERT(nvarchar,CAST((Case when (basic > @MaxAmount) then @MaxAmount ELSE Basic END) AS INT)),LEN(CONVERT(nvarchar,CAST((Case when (basic > @MaxAmount) then @MaxAmount ELSE Basic END) AS INT))) - 3)) + '000' ) AS INT ) * @Percentage / 100 * @NoOfMonths as Regular, 
                a.OfficeID 
            FROM 
                pmis.dbo.vw_RGPermanentAndCasual as a 
            LEFT JOIN 
                ifmis.dbo.tbl_R_BMSOffices as b ON b.PMISOfficeID = a.OfficeID 
            WHERE 
                a.OfficeID = @OfficeID AND a.EmploymentGroup = '1'

        INSERT INTO @TotalAmount 
            SELECT 
                SUM(CasualSalary) + SUM(RegularSalary) 
            FROM 
                @Casual as a 
            LEFT JOIN 
                @Regular as b ON b.OfficeID = a.OfficeID
    END
    ELSE IF(@Amount = 1)
    BEGIN
        INSERT INTO @TotalAmount 
            SELECT SUM(CasualSalary) as ELSE_IF 
            FROM @Casual
    END
END

/**SELECT CasualSalary FROM @Casual
SELECT RegularSalary FROM @Regular **/
SELECT TotalAmount FROM @TotalAmount

编辑:选择@Amount应为

SELECT @Amount = 1,@OfficeID = 72,@AccountID = 733, @NoOfMonths = 12, @Percentage = 1.25, @isRoundOf = 1, @MaxAmount = 35000, @EmployeeType = 1

1 个答案:

答案 0 :(得分:1)

正如您自己注意到的那样 - @AmountSELECT列表中列出了两次,其中包含两个不同的值。

轻松修复。 :)