zoukankan      html  css  js  c++  java
  • Sql server 通过汉字来获取对应拼音首字母的函数

    今天刚好同事遇到一个关于将 【药品名称】转换为【拼音简写】的问题,如:复方草珊瑚含片---FFCSHHP, 研究了以下,参考了网上的一些方法,写了如下的标量值函数来解决这个问题。

    create function fun_getPY(@str nvarchar(4000))
    returns nvarchar(4000)
    as
    begin
    declare @word nchar(1),@PY nvarchar(4000)
    set @PY=''
    while len(@str)>0
    begin
    set @word=left(@str,1)
    --- 如果为非汉字字符,返回原字符
    set @PY=@PY+(case when unicode(@word) between 19968 and 19968+20901
    then (select top 1 PY from (
    select 'A' as PY,N'' as word
    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''
    ) T
    where word>=@word collate Chinese_PRC_CS_AS_KS_WS
    order by PY ASC) else @word end)
    set @str=right(@str,len(@str)-1)
    end
    return @PY
    end

    将上面的Sql语句,复制到新建查询中运行即可,得到函数 dbo.fun_getPY()

    之后 用select 调用即可。演示操作如下:

     问题的核心点在这一句:

    case when unicode(@word) between 19968 and 19968+20901
    通过汉字的Unicode 编码来实现和拼音的一一对应,而在20901个汉字之外的其他字符会原封不动输出。

    注意点:
    union all select 'T',N'籜'
    加 N 就表示字符串用 Unicode 方式存储
  • 相关阅读:
    Codeforces Round #590 D. Distinct Characters Queries
    线段树模板加模板题POJ3468
    hihoCoder挑战赛5 C 与链
    HDU 5044 Tree 树链剖分
    HYSBZ 1901 Dynamic Rankings 树状数组套主席树
    POJ 2761 Feed the dogs 主席树
    POJ 2104 K-th Number 主席树 区间第K大
    HDU 4547 CD操作 LCA
    POJ 1470 Closest Common Ancestors 离线LCA
    HYSBZ 1036 树的统计Count 树链剖分 线段树
  • 原文地址:https://www.cnblogs.com/JesseP/p/11201070.html
Copyright © 2011-2022 走看看