Sql server 通过汉字来获取对应拼音首字母的函数

针对将药品名称转换为拼音简写的需求,本文分享了一个SQL标量值函数的实现方法。该函数通过判断字符的Unicode编码,对汉字进行拼音首字母转换,非汉字字符则直接输出。演示了如何创建及调用此函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天刚好同事遇到一个关于将 【药品名称】转换为【拼音简写】的问题,如:复方草珊瑚含片---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 方式存储

转载于:https://www.cnblogs.com/JesseP/p/11201070.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值