sql 全角 半角

来源:互联网 发布:mac php环境搭建 编辑:程序博客网 时间:2024/06/05 22:51
----------使用自定义函数进行转换
if object_id(N'U_ConvertSBCANDDBC',N'FN') is not null
 drop   function U_ConvertSBCANDDBC
GO 
/*
 转换原理 
全角字符unicode编码从65281~65374  
半角字符unicode编码从33~126  
空格比较特殊,全角为 12288,半角为   32  
而且除空格外,全角/半角按unicode编码排序在顺序上是对应的  
所以可以直接通过用+-法来处理非空格数据,对空格单独处理  
like的时候,指定排序规则   COLLATE   Latin1_General_BIN  
是保证字符顺序按unicode编码排序  


*/  
create   function   U_ConvertSBCANDDBC
(  
@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 
     begin 
       select   @pat=N'%[!-~]%',@step=-65248,  
       @str=replace(@str,N' ',N'   ')  
     end
    else  
     begin
       select   @pat=N'%[!-~]%',@step=65248,  
       @str=replace(@str,N'   ',N' ')  
     end
    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