2011-12-12 41 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