2011-08-09 117 views
2
 I have to remove the special characters from the selected string. 

例如:我有字符串'a & b'或'a & b'。我如何刪除特殊字符並將這些字符串連接成'ab'。刪除SQL中的特殊字符

請任何人都可以告訴我。

SELECT @id= (UPPER(SUBSTRING(@a,1,2)))+(UPPER(SUBSTRING((SELECT table.column2 FROM tablename WHERE tablename.column1 = @b),1,2))) + RIGHT('000000000' + CAST(@count as varchar(10)), 6) 
+0

** **剛剛'&'和空白或任何非字母字符? –

+1

[如何從SQL Server中的字符串中去除所有非字母字符?](http://stackoverflow.com/questions/1007697/how-to-strip-all-non-alphabetic-characters-from-string -in-sql-server) –

+0

包括任何非aplha字符 – Raj

回答

1

function是迄今爲止最好的選擇,如果你必須這樣做內聯,你可以遞歸CTE內更換和使用,作爲基表;

select 1 as id, 
     'qw2££!"£$%^&**(' as F into #TESTTABLE 
insert #TESTTABLE 
values (2, 'xxx'), 
     (3, ''), 
     (4,'$'), 
     (5,'qq""ee$$') 

;with cte(id, stripped) as (
    select id, cast(F as varchar(1024)) from #TESTTABLE 
    union all 
    select id, cast(stuff(stripped, patindex('%[^a-z]%', stripped), 1, '') as varchar(1024)) 
    from cte 
    where patindex('%[^a-z]%', stripped) > 0 
) 
select * from cte 
    where patindex('%[^a-z]%', stripped) = 0 
order by id 

結果:

>>id stripped 
>>1 qw 
>>2 xxx 
>>3 
>>4 
>>5 qqee 
+0

感謝您的重播...我有一個答案..鏈接ü給它它可以幫助我... – Raj

1
Declare @temp varchar(30) 
Set @temp = 'A & B' 
While PatIndex('%[^a-z]%', @Temp) > 0 
Set @Temp = Stuff(@Temp, PatIndex('%[^a-z]%', @Temp), 1, '') 

SELECT @id= (UPPER(SUBSTRING(@Temp,1,2)))+(UPPER(SUBSTRING((SELECT table.column2 FROM tablename WHERE tablename.column1 = @b),1,2))) + RIGHT('000000000' + CAST(@count as varchar(10)), 6) 
0
DECLARE @str VARCHAR(400) 
DECLARE @expres VARCHAR(50) = '%[~,@,#,$,%,&,*,(,),.,!]%' 
    SET @str = 'a&b' 
    WHILE PATINDEX(@expres, @str) > 0 
     SET @str = Replace(REPLACE(@str, SUBSTRING(@str, PATINDEX(@expres, @str), 1),''),'-',' ') 

    SELECT @str 

更多細節Click Here