- /**************************************************************
- * 转换原理:
- * 全角字符unicode编码从65281~65374
- * 半角字符unicode编码从33~126
- * 空格比较特殊,全角为12288,半角为32
- * 而且除空格外,全角/半角按unicode编码排序在顺序上是对应的
- * 所以可以直接通过用+-法来处理非空格数据,对空格单独处理
- * like的时候,指定排序规则 COLLATE Latin1_General_BIN
- * 是保证字符顺序按unicode编码排序
- ***************************************************************/
- create function u_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
- 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
- select dbo.u_convert('SX11SX',1) as [a],dbo.u_convert('sx11sx',0) as [b]
转载于:https://blog.51cto.com/lovgef/1186840