V
V
Vitaly Rybchenko2016-11-30 15:41:33
SQL Server
Vitaly Rybchenko, 2016-11-30 15:41:33

Is there an easier way to replace?

Have a nice day, everyone!
I have a need to check the value for the presence of characters and if they are in it, then replace them.
Now I do it like this:

select @Name = Name from #T
  set @Name = replace (@Name,'#','_')
  set @Name = replace (@Name,'%','_')
  set @Name = replace (@Name,'&','_')
  set @Name = replace (@Name,'{','_')
  set @Name = replace (@Name,'}','_')
  set @Name = replace (@Name,'\','_')
  set @Name = replace (@Name,'|','_')
  set @Name = replace (@Name,'/','_')
  set @Name = replace (@Name,'>','_')
  set @Name = replace (@Name,'<','_')
  set @Name = replace (@Name,'*','_')
  set @Name = replace (@Name,'?','_')
  set @Name = replace (@Name,'$','_')
  set @Name = replace (@Name,'!','_')
  set @Name = replace (@Name,'''','_')
  set @Name = replace (@Name,'"','_')
  set @Name = replace (@Name,':','_')
  set @Name = replace (@Name,'@','_')
  set @Name = replace (@Name,'+','_')
  set @Name = replace (@Name,'`','_')
  set @Name = replace (@Name,'=','_')
  set @Name = replace (@Name,'-','_')
  set @Name = replace (@Name,'  ',' ')
  set @Name = replace (@Name,'  ',' ')
  set @Name = replace (@Name,'  ',' ')
  set @Name = replace (@Name,char(13),' ')
  set @Name = replace (@Name,char(10),' ')

  select @Name

Maybe there are some easier ways? Any ideas?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Evseev, 2016-12-08
@biovr

Can.
The first option - replace can be nested like functional programming:
It does not look very good, but it can be broken into lines for readability.
The second option is more complicated, but more interesting:

declare @Name varchar(200) = 'abcdefg';

select @Name = replace(@Name, t.c, t.r)
from (
    values ('a','_'),('b','_'),('c','_')
) t(c,r)

print @Name

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question