ifexists (select*from dbo.sysobjects where id =object_id(N'[dbo].[LenN]') and xtype in (N'FN', N'IF', N'TF')) dropfunction[dbo].[LenN] GO SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GO --select dbo.lenN('adf') --drop function lenN createfunction LenN(@strvarchar(4000)) returnsint as begin --declare @str varchar(4000) declare @sTmpvarchar(8000),@iint,@itmpint,@itmp2int ,@stmp2varchar(2),@lenint --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