删除SQL中的特殊字符

时间:2011-08-09 10:55:08

标签: sql-server-2008

      I have to remove the special characters from the selected string.

例如:我有字符串'a& b'或'a& amp; B”。如何删除特殊字符并将这些字符串连接成'ab'。

请任何人告诉我。

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) 

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

答案 2 :(得分: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