小写字母与大写字母具有相同的 ASCII 或 UNICODE 值,但小写字母的位标志设置为 32。
这很容易直接检测,或者将检测包装到用户定义的函数中,如 IsUpper() 和 IsLower()。
示例(注意 ASCII() 和 UNICODE() 在这里可以互换使用):
DECLARE @Letter char(1);
SET @Letter = 'A'
PRINT
@Letter + space(1) +
CASE
WHEN (UNICODE(@Letter) & 32 > 0) THEN 'is lower case'
ELSE 'is UPPER CASE'
END
SET @Letter = 'z'
PRINT
@Letter + space(1) +
CASE
WHEN (ASCII(@Letter) & 32 > 0) THEN 'is lower case'
ELSE 'is UPPER CASE'
END
-- Output:
-- A is UPPER CASE
-- z is lower case
此函数将使用递归 CTE 查找整个字符串中的任何大写字母:
CREATE FUNCTION [dbo].[ContainsUpper](@InputString [varchar](80))
RETURNS [bit] WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @Result bit = 0,
@LowerString varchar(80) = lower(@InputString);
WITH Letters
AS
(
SELECT Position = 1,
IsUpper =
CASE unicode(left(@InputString,1))
WHEN unicode(left(@LowerString,1)) THEN 0
ELSE 1
END
UNION ALL
SELECT Position = Position + 1,
IsUpper =
CASE unicode(substring(@InputString, Position + 1, 1))
WHEN unicode(substring(@LowerString, Position + 1, 1)) THEN 0
ELSE 1
END
FROM Letters
WHERE Position < len(@InputString)
)
SELECT @Result = max(convert(int, IsUpper))
FROM Letters
RETURN @Result
END