2011-12-12 7 views
9

ループ/カスタム機能なしでSQLサーバーの文字列/フィールドから特殊文字(英数字のみ)を削除する方法はありますか?ループのないSQLの特殊文字を削除しますか?

はこれまでのところ、私が思い付くした最高のは、次のとおりですので、私は達成することができるようにしたいのですが、私は、ユーザー定義関数をCREADする権限を持っていないいくつかのサーバーで

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 

同じ結果なし。 私はループの効率/性能についても懸念しています(組み込みの関数/メソッドでさえおそらくループを使用すると思いますが)。

おかげ

+1

のような言語では動作しませんバック英数字に物事をストリッピング多言語の要件を持っています。 [興味深い議論があります](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-z0-9]% ''の代わりに' '[[A-Za-z0-9]%'' ' –

0

その他REPLACEステートメントはこれが私が思い付く最高のものです。 私たちは、私はsoemtimes人々は事のように、テーブルに文字列を分解し、キーパーの文字のテーブルに参加することをお勧め見てきたアラビア

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 
関連する問題