轉:Sqlserver 全形/半形轉換

來源:互聯網
上載者:User
Code
if   exists   (select   *   from   dbo.sysobjects   where   id   =   object_id(N'[dbo].[f_convert]')   and   xtype   in   (N'FN',   N'IF',   N'TF'))  
drop   function   [dbo].[f_convert]  
GO  
 
/*--全形/半形轉換  
 
轉換說明  
全形字元從的unicode編碼從65281~65374  
半形字元從的unicode編碼從     33~126  
空格比較特殊,全形為   12288,半形為   32  
而且除空格外,全形/半形按unicode編碼排序在順序上是對應的  
所以可以直接通過用+-法來處理非空格資料,對空格單獨處理  
like的時候,指定定序   COLLATE   Latin1_General_BIN  
是保證字元順序按unicode編碼排序  

 
declare   @s1   varchar(8000)  
select   @s1='中    2-3456a78STUVabn中國opwxyz'  
select   dbo.f_convert(@s1,0),dbo.f_convert(@s1,1)  
*/  
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) 

*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.