一、该函数传入字符串,返回数据为:如果为汉字字符,返回该字符的首字母,如果为非汉字字符,则返回本身。
二、用到的知识点:汉字对应的UNICODE值,汉字的排序规则。
三、数据库函数:
CREATE FUNCTION GetInitialLetter(@ChineseString NVARCHAR(4000)) RETURNS NVARCHAR(4000) AS BEGIN DECLARE @SingleCharacter NCHAR(1), @ReturnString NVARCHAR(4000) SET @ReturnString = '' WHILE LEN(@ChineseString)>0 BEGIN --依次取单个字符 SET @SingleCharacter = LEFT(@ChineseString,1) ----汉字字符,返回字符对应首字母,非汉字字符,返回原字符 IF(UNICODE(@SingleCharacter) BETWEEN 19968 AND 19968+20901) SET @ReturnString = @ReturnString + (SELECT TOP 1 PY FROM (SELECT 'A' AS PY,N'骜' AS ChineseCharacters UNION All SELECT 'B',N'簿' UNION All SELECT 'C',N'错' UNION All SELECT 'D',N'鵽' UNION All SELECT 'E',N'樲' UNION All SELECT 'F',N'鳆' UNION All SELECT 'G',N'腂' UNION All SELECT 'H',N'夻' UNION All SELECT 'J',N'攈' UNION All SELECT 'K',N'穒' UNION All SELECT 'L',N'鱳' UNION All SELECT 'M',N'旀' UNION All SELECT 'N',N'桛' UNION All SELECT 'O',N'沤' UNION All SELECT 'P',N'曝' UNION All SELECT 'Q',N'囕' UNION All SELECT 'R',N'鶸' UNION All SELECT 'S',N'蜶' UNION All SELECT 'T',N'箨' UNION All SELECT 'W',N'鹜' UNION All SELECT 'X',N'鑂' UNION All SELECT 'Y',N'韵' UNION All SELECT 'Z',N'咗' )SpellingTable where ChineseCharacters > = @SingleCharacter COLLATE Chinese_PRC_CS_AS_KS_WS ORDER by PY ASC) ELSE SET @ReturnString = @ReturnString + @SingleCharacter SET @ChineseString = RIGHT(@ChineseString,LEN(@ChineseString)-1) END RETURN @ReturnString END GO
四、函数调用:
SELECT dbo.GetInitialLetter('中华人民共和国(1949 - 2016)') 返回: ZHRMGHG(1949 - 2016)
后记说明:
1、unicode 字符是国际组织制定的可以容纳世界上所有文字和符号的字符编码方案,世界上的任何字符都有唯一对应的一组十六进制表示(例 ‘汉’:6C49),汉字对应的范围转换为十进制之后是:19968 - 40869.
2、临时表 SpellingTable 字段 ChineseCharacters 中存储的汉字,以对应的 PY 字段开头的汉语拼音的最后一个汉字。 可查新华字典:http://xh.5156edu.com/pinyi.html