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 方式存储
  • 相关阅读:
    搭建负载均衡的环境(利用虚拟机上的四台centos)
    java的IO,AIO简单对比
    【每日分享】关于漏测
    安装xampp后,遇到的各种问题
    端口占用问题——netstat命令
    随笔
    AJAX 状态值(readyState)与状态码(status)详解
    CSS 实践:实现下拉菜单的方法
    css3动画总结
    判断手机运营商
  • 原文地址:https://www.cnblogs.com/JesseP/p/11201070.html
Copyright © 2011-2022 走看看