Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace nth character in sql server

I am trying to replace the nth character in SQL Server. I tried with it using replace():

SELECT REPLACE(ABC,0,1)  FROM XXX 

In above code all zeros will be replaced with one, but I only want to change it in a particular position and sometimes that position can change.

like image 215
Imran Zain Avatar asked Feb 23 '15 13:02

Imran Zain


People also ask

How do you replace a specific character in SQL?

SQL Server REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive.

How do I change the first 3 characters in SQL?

In a view, you could do it like: select case when col1 like '00%' then stuff(col1, 1, 2, '11') else col1 end from YourTable; Live example at SQL Fiddle. Just a note, the substring should be "substring(col1, 3, len(col1)-2)"because you want to start at 3rd character and the characters are numbered from 1, not 0.

How do I replace multiple characters in a string in SQL Server?

If you wanted to replace the words with blank string, go with REGEXP_REPLACE() . If you want to replace the words with other words, for example replacing & with and then use replace() . If there are multiple words to be replaced, use multiple nested replace() .


2 Answers

use stuff The STUFF function 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.

select STUFF(ABC, starting_index, 1, 'X') from XXX 

"Here your int position to replace" is the position no just replace with any int no and that position will be replaced Note : (Thanks to pcnate for suggestion) starting_index is your int position to replace.

like image 190
Imran Ali Khan Avatar answered Sep 24 '22 08:09

Imran Ali Khan


You're looking for STUFF:

select STUFF(ABC, @n, 1, 'X') from XXX 

This would replace the @nth character with an X.

Technically it seeks into the original string at column ABC starting at position @n, deletes 1 character, then inserts the string 'X' at that position.

like image 41
lc. Avatar answered Sep 22 '22 08:09

lc.