0

如何计算两个字符之间的字母数(按字母顺序从 a 到 z 或 z 到 a)?

例如:

WITH    ExampleData
          AS ( SELECT   'a' AS StartChar, 'e' AS EndChar
               UNION ALL
               SELECT   'm', 'r'
               UNION ALL
               SELECT   'f', 'a'
             )
    SELECT  StartChar ,
            EndChar
    FROM    ExampleData

需要生产:

StartChar   EndChar    Diff
a           e          4
m           r          5
f           a          -5

我看到如何使用 udf 和 while 循环轻松完成此操作,但我想知道是否有更快的方法?

4

4 回答 4

6
SELECT StartChar, EndChar, ASCII(EndChar) - ASCII(StartChar) AS Diff
FROM ExampleData

SQL 小提琴示例

于 2012-11-07T17:11:38.597 回答
0

假设您已经对 StartChar 和 EndChar 进行了有效性检查...

SELECT ASCII(EndChar) - ASCII(StartChar) as Diff
于 2012-11-07T17:11:56.380 回答
0

这应该可以为您完成工作:

WITH    ExampleData
          AS ( SELECT   'a' AS StartChar, 'e' AS EndChar
               UNION ALL
               SELECT   'm', 'r'
               UNION ALL
               SELECT   'f', 'a'
             )
    SELECT  StartChar ,
            EndChar, ascii(EndChar) - ascii(StartChar) as Diff
    FROM    ExampleData
于 2012-11-07T17:13:16.750 回答
0

CTE真是太棒了!如果您不想使用 ASCII,那么您可以这样做:

;   With    CharCodes   (
    Code
)   As          (
    Select  65
Union   All
    Select  Code
    +   1
        From    CharCodes
        Where   Code        <   90
)
    Select  Second.Code
    -   First.Code
        From    CharCodes   As  First
        ,   CharCodes   As  Second
        Where   First.Code  =   Convert(Int, Convert(VarBinary, 'A'))
        And Second.Code =   Convert(Int, Convert(VarBinary, 'E'))

使用 ASCII 函数,您可以这样做:

Select  ASCII('E')
-   ASCII('A')
于 2012-11-07T17:13:46.427 回答