Home  >  Article  >  Database  >  SQLSERVER中的全角和半角

SQLSERVER中的全角和半角

WBOY
WBOYOriginal
2016-06-07 15:52:061459browse

/*--全角/半角转换 转换说明 全角字符从的unicode编码从65281~65374 半角字符从的unicode编码从 33~126 空比较特殊,全角为 12288,半角为 32 而且除空外,全角/半角按unicode编码排序在顺序上是对应的 所以可以直接通过用-法来处理非空数据,对空单独处理 like

 /*--全角/半角转换

转换说明
全角字符从的unicode编码从65281~65374
半角字符从的unicode编码从 33~126
空格比较特殊,全角为 12288,半角为 32
而且除空格外,全角/半角按unicode编码排序在顺序上是对应的
所以可以直接通过用+-法来处理非空格数据,对空格单独处理
like的时候,指定排序规则 COLLATE Latin1_General_BIN
是保证字符顺序按unicode编码排序

 

创建以下函数


Create FUNCTION f_Convert(
@str NVARCHAR(4000), --要转换的字符串
@flag bit --转换标志,0转换成半角,1转换成全角
)RETURNS nvarchar(4000)
AS
BEGIN
DECLARE @pat nvarchar(8),@step int,@i int,@spc int
IF @flag=0
Select @pat=N'%[!-~]%',@step=-65248,
@str=REPLACE(@str,N' ',N' ')
ELSE
Select @pat=N'%[!-~]%',@step=65248,
@str=REPLACE(@str,N' ',N' ')
SET @i=PATINDEX(@pat COLLATE LATIN1_GENERAL_BIN,@str)
WHILE @i>0
Select @str=REPLACE(@str,
SUBSTRING(@str,@i,1),
NCHAR(UNICODE(SUBSTRING(@str,@i,1))+@step))
,@i=PATINDEX(@pat COLLATE LATIN1_GENERAL_BIN,@str)
RETURN(@str)
END
GO

 

示例:

declare @s1 varchar(8000)
select @s1='中  2-3456a78STUVabn中国opwxyz'
select dbo.f_convert(@s1,0),dbo.f_convert(@s1,1)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn