【转载】SQL SERVER 中单字节和双字节互转自定义函数(全角半角转换)

一、首先创建一个自定义函数,代码如下:

复制代码
alter function f_convert(
@str nvarchar(4000), --要转换的字符串
@flag bit            --转换标志,0转换成半角,1转换成全角
)
returns nvarchar(max)
as
begin
  declare @pat nvarchar(8),@step int,@i int,@spc int
  if @flag=0
    select @pat=N'%[!-~ ]%',@step=-65248
  else
    select @pat=N'%[!-~ ]%',@step=65248
  set @i=patindex(@pat COLLATE Latin1_General_BIN,@str)
  while @i>0
    select @str=stuff(@str,@i,1,nchar(case unicode(substring(@str,@i,1))
    when 32 then 12288
    when 12288 then 32
    else unicode(substring(@str,@i,1))+@step end))
    ,@i=patindex(@pat COLLATE Latin1_General_BIN,@str)
  return(@str)
end
go
复制代码

2、函数创建完成后,就可以用select语句测试啦,测试代码如下:

 -- 单字节转双字节
 select  dbo.f_convert('abcd1234:单字节转双字节',1)
 -- 双字节转单字节
 select  dbo.f_convert('abcd1234:单字节转双字节',0)

 

* 3、VFP中对应的函数为:
* ======================
strconv(cExpression,1)
strconv(cExpression,2)  

 

posted @   深海澜鲸  阅读(305)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示