1. /************************************************************** 
  2.     * 转换原理:  
  3.     * 全角字符unicode编码从65281~65374   
  4.     * 半角字符unicode编码从33~126   
  5.     * 空格比较特殊,全角为12288,半角为32   
  6.     * 而且除空格外,全角/半角按unicode编码排序在顺序上是对应的   
  7.     * 所以可以直接通过用+-法来处理非空格数据,对空格单独处理   
  8.     * like的时候,指定排序规则 COLLATE Latin1_General_BIN   
  9.     * 是保证字符顺序按unicode编码排序   
  10. ***************************************************************/   
  11. create function u_convert(   
  12. @str nvarchar(4000),   --要转换的字符串   
  13. @flag bit              --转换标志,0转换成半角,1转换成全角   
  14. returns nvarchar(4000)   
  15. AS   
  16. begin   
  17.     declare    
  18.           @pat nvarchar(8), 
  19.           @step int
  20.           @i int
  21.           @spc int   
  22.     if  @flag=0  
  23.         begin  
  24.             select @pat=N'%[!-~]%',@step=-65248,   
  25.             @str=replace(@str,N' ',N'   ')   
  26.         end 
  27.     else   
  28.         begin 
  29.             select @pat=N'%[!-~]%',@step=65248,   
  30.             @str=replace(@str,N'   ',N' ')   
  31.         end 
  32.     set @i=patindex(@pat collate LATIN1_GENERAL_BIN,@str)   
  33.     while @i>0   
  34.        select @str=replace(@str,   
  35.             substring(@str,@i,1),  
  36.             nchar(unicode(substring(@str,@i,1))+@step)), 
  37.             @i=patindex(@pat collate LATIN1_GENERAL_BIN,@str)   
  38.      return(@str)   
  39. end   
  40. GO 
  41.   
  42. select dbo.u_convert('SX11SX',1) as [a],dbo.u_convert('sx11sx',0) as [b]