任何其他方式来避免if else条件

时间:2014-12-05 00:18:01

标签: sql sql-server

我有以下存储过程。我有变量@PercentCleared

IF @PercentCleared <= 70然后我必须减去PercentCleared-10其他用途。你能告诉我正确的方法吗?

    DECLARE @PercentCleared INT
    DECLARE @TenPercent int

    SET @TenPercent = 10

    IF(@PercentCleared <=70)
    BEGIN
        SELECT 
            @I, dbo.tblV.VegTypeCode, dbo.tblV.VegTypeName 
        FROM 
            dbo.tblVegetationType 
        INNER JOIN 
            dbo.tblVegFormationLink ON dbo.tblV.VegTypeID = dbo.tblVegFormationLink.VegTypeID
        WHERE   
            dbo.tblVegetationType.PercentageCleared >=(@PercentCleared - @TenPercent)
        WHERE 
            a.VegTypeID = dbo.tblVegetationType.VegTypeID 
            AND dbo.tblVegetationType.VegTypeID <> (SELECT VegTypeID 
                                                    FROM @EcosystemCredits eco 
                                                    WHERE eco.theID = @I) 
    END
    ELSE IF
    BEGIN
        SELECT 
            @I, dbo.tblV.VegTypeCode, dbo.tblV.VegTypeName
        FROM 
            dbo.tblVegetationType 
        INNER JOIN 
            dbo.tblVegFormationLink ON dbo.tblV.VegTypeID = dbo.tblVegFormationLink.VegTypeID
        WHERE   
            dbo.tblVegetationType.PercentageCleared >=@PercentCleared
        WHERE 
            a.VegTypeID = dbo.tblVegetationType.VegTypeID 
            AND dbo.tblVegetationType.VegTypeID <> (SELECT VegTypeID 
                                                    FROM @EcosystemCredits eco WHERE eco.theID = @I) 

    End

3 个答案:

答案 0 :(得分:2)

我认为您可以通过在WHERE子句

中使用CASE语句来完成此操作
SELECT @I,  dbo.tblV.VegTypeCode,  dbo.tblV.VegTypeName FROM dbo.tblVegetationType 
INNER JOIN dbo.tblVegFormationLink
  ON dbo.tblV.VegTypeID = dbo.tblVegFormationLink.VegTypeID
WHERE dbo.tblVegetationType.PercentageCleared 
      >= @PercentCleared 
         - CASE WHEN (@PercentCleared <=70) THEN @TenPercent ELSE 0 END -- change here
WHERE a.VegTypeID = dbo.tblVegetationType.VegTypeID 
AND dbo.tblVegetationType.VegTypeID 
    <> (SELECT VegTypeID FROM @EcosystemCredits eco WHERE eco.theID = @I) 

答案 1 :(得分:2)

您可以将逻辑放在where子句中。

SELECT @I,  dbo.tblV.VegTypeCode, vt.VegTypeName
FROM dbo.tblVegetationType vt INNER JOIN
     dbo.tblVegFormationLink vfl
     ON vt.VegTypeID = vlt.VegTypeID
WHERE (vt.PercentageCleared >= @PercentCleared - (CASE WHEN @PercentCleared <= 70 THEN @TenPercent ELSE 0 END)) AND
      (vt.VegTypeID <> (SELECT VegTypeID FROM @EcosystemCredits eco WHERE eco.theID = @I) );

我使用表别名简化了查询。此外,您有两个where条款,第二个条款是多余的。

答案 2 :(得分:0)

您可以在没有 CASE IF 语句的情况下通过重写这样的SQL来实现这一目标......

WHERE   
    (@PercentCleared <=70 AND dbo.tblVegetationType.PercentageCleared >=(@PercentCleared - @TenPercent))
OR
    (@PercentCleared > 70 AND dbo.tblVegetationType.PercentageCleared >= @PercentCleared)

希望它不仅有助于这种情况,还有许多类似的情况。