Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing only the nth instance of character

Is there a way a can replace the 1st instance of a character in a string with something eg.

^1402 WSN NIAMLAB^teertS htimS 005

to be

&1402 WSN NIAMLAB^teertS htimS 005

keeping the second ^ in place

like image 279
HL8 Avatar asked Jan 13 '12 04:01

HL8


1 Answers

To replace the first instance of a character I would recommend the use of the STUFF and CHARINDEX functions. STUFF inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

DECLARE @str varchar(100) = '^1402 WSN NIAMLAB^teertS htimS 005'
SELECT STUFF(@str, CHARINDEX('^', @str), 1, '&')

Note that you could also use STUFF in a query as follows:

SELECT STUFF(<yourcolumn>, CHARINDEX('^', <yourcolumn>), 1, '&')
FROM <yourtable>
like image 187
Phil Klein Avatar answered Oct 26 '22 21:10

Phil Klein