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 方式存储
  • 相关阅读:
    centos7系统最小系统安装并配置网络
    解决 JAAVA springboot 数据存储到数据库数据显示??的方案
    vue scoped
    Vue插件
    Git命令学习
    深度拷贝
    ES6学习_简化对象写法
    ES6学习_字符串的拼接
    ES6学习_变量的解构赋值
    ES6学习_const关键字
  • 原文地址:https://www.cnblogs.com/JesseP/p/11201070.html
Copyright © 2011-2022 走看看