获取含中文的真实字节长度

本文介绍了一个 SQL Server 中自定义的函数 LenN,该函数用于计算字符串中每个字符的实际字节长度,并据此返回字符串的真实长度。对于中文字符和其他特殊字符的处理尤其重要。

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

 
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LenN]'and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[LenN]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--select dbo.lenN('adf')
--
drop function lenN
create function LenN(@str varchar(4000)) 
returns  int
as
begin
 
--declare @str varchar(4000)
 declare
 
@sTmp varchar(8000),@i int,@itmp int,@itmp2 int ,@stmp2 varchar(2),@len int
 
--select @str='中国ren'
 select @sTmp='',@len=0
 
select @i=1
 
while @i<=len(@str)
  
begin
     
select @len=@len+1
     
select @itmp=convert(int,substring(convert(varbinary,substring(@str ,@i,1)),1,1)) --截取一个字节
     if @itmp>127  
     
begin
       
--大于127检查后面一个字节
       select @itmp2=convert(int,substring(convert(varbinary,substring(@str ,@i,1)),2,1))
       
if @itmp2>127
       
begin
  
select @len=@len+1
         
select @stmp2=char(@itmp)+char(@itmp2)   --是一个完整的汉字 
      end 
      
   
end
 
select @i=@i+1
 
end  
       
return @len
end




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值