2017-08-14 34 views
1

我想使這個適當的工作代碼更漂亮一點。如何簡化大CASE語句?

SET @weightClass = CASE 
    WHEN @totalWeight < 50 THEN 'A' 
    WHEN @totalWeight < 100 THEN 'B' 
    WHEN @totalWeight < 150 THEN 'C' 
    WHEN @totalWeight < 200 THEN 'D' 
    WHEN @totalWeight < 250 THEN 'E' 
    WHEN @totalWeight < 300 THEN 'F' 
    WHEN @totalWeight < 350 THEN 'G' 
    WHEN @totalWeight < 400 THEN 'H' 
    WHEN @totalWeight < 450 THEN 'I' 
    WHEN @totalWeight < 500 THEN 'J' 
    WHEN @totalWeight < 550 THEN 'K' 
    WHEN @totalWeight < 600 THEN 'L' 
    WHEN @totalWeight < 650 THEN 'M' 
    WHEN @totalWeight < 700 THEN 'N' 
    WHEN @totalWeight < 750 THEN 'O' 
    WHEN @totalWeight < 800 THEN 'P' 
    WHEN @totalWeight < 850 THEN 'Q' 
    WHEN @totalWeight < 900 THEN 'R' 
    WHEN @totalWeight < 950 THEN 'S' 
    ELSE 'T' 
END 

我想有可能是使用字母和50的邏輯增量的ASCII值沒有可能(和可行的),使這個辦法?如何以及是否會顯着減慢查詢速度?

+0

可能while循環?並且由於增量按照字母順序排列,所以它不應該太難以使其工作。 – imBlue

+0

定義一個weightClass表,可能有獨佔的權重範圍,加入一個條件之間。 – user6144226

回答

7

的函數來獲取的字符是CHAR()
對於A的ASCII碼是65

SELECT CASE 
    WHEN @totalWeight >= 950 THEN 'T' 
    ELSE CHAR(@totalWeight/50 + 65) 
END 
+0

我會如何在'T'封頂? – Danieboy

+1

我認爲應該是+65。當我運行49的值,否則我會得到'@'。編輯:像這樣:SELECT CHAR((@ totalWeight/50)+ 65) – Danieboy

+0

@Danieboy - 我認爲你是對的!它下降到0(整數部分)。我的錯。修正並更新以尊重'T' – AjahnCharles