• 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 方式存储
  • 相关阅读:
    真的是简单、简洁、简易、简明之道!!!
    HashMap源码解读
    Jenkins Pipeline
    C语言二级指针free|一级指针存储内存地址
    openjdk编译和调试,JVM编译调试
    java linux和win jdk安装包jdk1.6、jdk1.7和jdk1.8 7u80 8u181 8u161
    关于java代码打包成jar在控制台运行变慢的问题
    Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen
    mongodb副本集
    condition
  • 原文地址:https://www.cnblogs.com/JesseP/p/11201070.html
Copyright © 2020-2023  润新知