2014-12-05 63 views
0

我有一個以下的存儲過程。我有變量@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 >[email protected] 
     WHERE 
      a.VegTypeID = dbo.tblVegetationType.VegTypeID 
      AND dbo.tblVegetationType.VegTypeID <> (SELECT VegTypeID 
                FROM @EcosystemCredits eco WHERE eco.theID = @I) 

    End 
+0

這很難讀。你可以重新格式化更清晰嗎? (我很抱歉,但我沒有能力爲你做這件事。)@ TenPercent這個名字並不是一個很好的選擇。要麼寫10或者給它一個更有意義的名字。 – 2014-12-05 00:20:11

+0

對不起喬納森,我現在正在格式化 – Usher 2014-12-05 00:23:05

+0

'else if'是否只是'其他'? 'else if'的'if'部分沒有條件。雖然這是瑣事。其餘的更容易閱讀。你不能在SELECT語句之一中使用'CASE @PercentCleared WHEN> = 70 THEN @PercentCleared - @TenPercent ELSE @PercentCleared END'來代替'@ PercentCleared'條件,所以你不需要其他或外部IF/ELSE。 – 2014-12-05 00:33:31

回答

2

我想你可以通過在WHERE子句

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) 
2

使用CASE語句,你可以把邏輯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子句,第二個是多餘的。

0

你可以做到這一點沒有CASEIF聲明通過重新編寫SQL這樣的...

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

希望它不僅有助於在這種情況下,但許多類似situtations。