如何计算两个字符之间的字母数(按字母顺序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循环轻松完成,但我想知道是否有更快的方法?
答案 0 :(得分:6)
SELECT StartChar, EndChar, ASCII(EndChar) - ASCII(StartChar) AS Diff
FROM ExampleData
答案 1 :(得分:0)
假设您已经对StartChar和EndChar进行了有效性检查......
SELECT ASCII(EndChar) - ASCII(StartChar) as Diff
答案 2 :(得分: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
答案 3 :(得分: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')