--这样处理就行了.select substring(col ,patindex('%[^ ]%',col) ,len(col)-patindex('%[^ ]%',reverse(rtrim(col)))-patindex('%[^ ]%',col)+2) from( select col='a' union all select ' a' union all select ' a ' union all select ' a ' union all select ' a ' union all select '' )a/*--测试结果
----- a a a a a (所影响的行数为 6 行) --*/
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编码排序 (此函数部分思路参考了CSDN上大力的转换函数) --邹建 2005.01(引用请保留此信息)--*//*--调用示例 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 else select @pat=N'%[!-~ ]%',@step=65248 set @i=patindex(@pat COLLATE Latin1_General_BIN,@str) while @i>0 select @str=stuff(@str,@i,1,nchar(case unicode(substring(@str,@i,1)) when 32 then 12288 when 12288 then 32 else unicode(substring(@str,@i,1))+@step end)) ,@i=patindex(@pat COLLATE Latin1_General_BIN,@str) return(@str) end go
--这样处理就行了.select substring(col
,patindex('%[^ ]%',col)
,len(col)-patindex('%[^ ]%',reverse(rtrim(col)))-patindex('%[^ ]%',col)+2)
from(
select col='a'
union all select ' a'
union all select ' a '
union all select ' a '
union all select ' a '
union all select ''
)a/*--测试结果
-----
a
a
a
a
a
(所影响的行数为 6 行)
--*/
drop function [dbo].[f_convert]
GO/*--全角/半角转换转换说明
全角字符从的unicode编码从65281~65374
半角字符从的unicode编码从 33~126
空格比较特殊,全角为 12288,半角为 32
而且除空格外,全角/半角按unicode编码排序在顺序上是对应的
所以可以直接通过用+-法来处理非空格数据,对空格单独处理
like的时候,指定排序规则 COLLATE Latin1_General_BIN
是保证字符顺序按unicode编码排序
(此函数部分思路参考了CSDN上大力的转换函数)
--邹建 2005.01(引用请保留此信息)--*//*--调用示例 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
else
select @pat=N'%[!-~ ]%',@step=65248
set @i=patindex(@pat COLLATE Latin1_General_BIN,@str)
while @i>0
select @str=stuff(@str,@i,1,nchar(case unicode(substring(@str,@i,1))
when 32 then 12288
when 12288 then 32
else unicode(substring(@str,@i,1))+@step end))
,@i=patindex(@pat COLLATE Latin1_General_BIN,@str)
return(@str)
end
go