2011-12-12 39 views
9

有没有一种方法来脱离SQL服务器中的字符串/字段的特殊字符(只留下字母数字),没有循环/自定义函数?删除SQL中没有循环的特殊字符?

到目前为止,我想出最好的是:

Create Function [dbo].[strip_special](@Temp VarChar(1000)) 
Returns VarChar(1000) 
AS 
Begin 
    While PatIndex('%[^a-z0-9]%', @Temp) > 0 
     Set @Temp = Stuff(@Temp, PatIndex('%[^a-z0-9]%', @Temp), 1, '') 
    Return @TEmp 
End 

在某些服务器上我没有的特权CREAD用户自定义函数,所以我希望能够实现相同的结果没有。 我也担心循环的效率/性能(尽管我猜即使是内置的函数/方法本身也可能会使用循环)。

感谢

+1

我soemtimes看到有人建议拆卸串似的东西表并加入到门将字符表。 [这里是你可能感兴趣的讨论](http://ask.sqlservercentral.com/questions/75404/strip-all-but-alpha-chars-out-of-a-string) –

回答

6

我假设你有想要更换一列,这是你如何能做到这一点:

declare @table table(id int, temp varchar(15)) 


insert @table values(1, 'abc-.123+') 
insert @table values(2, '¤%&(abc-.?=&(/#') 

;with t1 as 
(
select temp a, id from @table 
union all 
select cast(replace(a, substring(a, PatIndex('%[^a-z0-9]%', a), 1), '') as varchar(15)), id 
from t1 
where PatIndex('%[^a-z0-9]%', a) > 0 
) 
select t2.*, t1.a from t1 
join @table t2 
on t1.id = t2.id 
where PatIndex('%[^a-z0-9]%', a) = 0 
option (maxrecursion 0) 

结果:

id   temp   a 
----------- --------------- --------------- 
2   ¤%&(abc-.?=&(/# abc 
1   abc-.123+  abc123 
1

如果你想做得更快,使用此功能。

如果您需要在没有函数的情况下使用它,您可能需要使用游标一次获取每一行,并为每一行应用下一个函数的内容。

create function dbo.strip_special(@s varchar(256)) returns varchar(256) 
    with schemabinding 
begin 
    if @s is null 
     return null 
    declare @s2 varchar(256) 
    set @s2 = '' 
    declare @l int 
    set @l = len(@s) 
    declare @p int 
    set @p = 1 
    while @p <= @l begin 
     declare @c int 
     set @c = ascii(substring(@s, @p, 1)) 
     if @c between 48 and 57 or @c between 65 and 90 or @c between 97 and 122 
     set @s2 = @s2 + char(@c) 
     set @p = @p + 1 
     end 
    if len(@s2) = 0 
     return null 
    return @s2 

    end 
+3

为什么这会更快?我会认为你的函数必须为输入的每个字符循环,而我的函数将只循环每个非字母数字字符? –

+0

你也可以使用你的功能。但在这种情况下,你不应该使用'%[^ A-Za-z0-9]%''而不是''%[^ a-z0-9]%''? –

0

除具有嵌套一大堆其他REPLACE语句是我能想到的最好的语句。 我们拥有多语种的要求,所以剥离东西还给字母数字的语言,如阿拉伯语不起作用

DECLARE 
    @OrgString nVarchar(max), 
    @Pattern nvarchar(max) 


SET @OrgString = N'~,`,!,@,#,$,%,^,&,*,(,),0-9,_,-,+,=,[,],{,},;,:,",<,>,?,/,\,|حساب "خارج الميز1$انية"' 
SET @Pattern = '%[~,`,!,@,#,$,%,^,&,*,(,),0-9,_,''-,+,=,[,{,},;,:,",<,>,?,/,\,|]%' 


WHILE PATINDEX(@Pattern, @OrgString) > 0 
    SET @OrgString = REPLACE(@OrgString, SUBSTRING(@OrgString, PATINDEX(@Pattern, @OrgString), 1), '') 
SELECT REPLACE(@OrgString, ']', '') -- Cant workout how to put ] in @Pattern