Tuesday, February 16, 2010

Search and Replace last occurence of the word


This SQL query is to search a text in varchar field and replace with the given text

Here @field is the table field, we are using now() -- current timestamp
@search is the search pattern, we are searching for number 2
@replace is what we want to replace the search pattern with we are replacing with A

select @field:=now() `field`,@search:='2' `search`, @replace:='A' `replace`,
@fieldr:=reverse(@field) `l`, @searchr:=reverse(@search) `l`, @lengthf:=length(@field) `l`, @lengths:=length(@search)-1 `l`,
concat(left(@field,@lengthf-locate(@searchr,@fieldr)-@lengths),@replace,right(@field,locate(@searchr,@fieldr)-1)) `finalfield`

We can see what is in field has replacement done in finalfield

No comments:

Post a Comment