Skip to content
Advertisement

SQL REPLACE special characters with value from another table

All,

I am trying to replace the special characters in a string with the URL encoding values to which they correspond. Below is some example code I have been working with.

Thanks for the help.

create table #url_encoding_lookup(character varchar(10), code varchar (20))

insert into  #url_encoding_lookup (character, code)
values 
('!',   '%21'),
('"',   '%22'),
('#',   '%23'),
('$',   '%24'),
('%',   '%25'),
('&',   '%26'),
('''',  '%27'),
('(',   '%28'),
(')',   '%29'),
('*',   '%2A'),
('+',   '%2B'),
(',',   '%2C'),
('-',   '%2D'),
('.',   '%2E'),
('/',   '%2F')


Create   table #data
(string varchar (200))

insert into #data
values

('Jim (BoB)'),
('Will''s Place'),
('Auto-Mart')


select * from #data
select * from #url_encoding_lookup

desired results would be 

Jim %28Bob%29
Will%27s Place
Auto%2DMart

Advertisement

Answer

Create procedure

BEGIN 
  DECLARE _end BOOLEAN DEFAULT FALSE;
  DECLARE _result CHAR(200) DEFAULT str; 
  DECLARE _find VARCHAR(32);
  DECLARE _replace VARCHAR(32);
  DECLARE _cur CURSOR FOR SELECT _character, _code FROM url_encoding_lookup; 
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET _end = TRUE; 

  OPEN _cur; 
    _loop: LOOP 
      FETCH _cur INTO _find, _replace; 
        IF _end THEN 
          LEAVE _loop; 
        END IF; 
       SET _result = REPLACE(_result, _find, _replace);
     END LOOP _loop; 
  CLOSE _cur; 
  RETURN _result; 
END

Then

SELECT _replace_chars(name) FROM `data`

Result

Jim %28BoB%29
Will%27s Place
Auto%2DMart
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement