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.
6条答案
按热度按时间eni9jsuy1#
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.
"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.
3lxsmp7m2#
You're looking for
STUFF
:This would replace the
@n
th character with anX
.Technically it seeks into the original string at column
ABC
starting at position@n
, deletes1
character, then inserts the string'X'
at that position.tf7tbtn23#
You use
STUFF
for this:This would replace the 5th character with a 1.
b1uwtaje4#
Use
stuff()
:It is documented here .
lstz6jyr5#
Use Stuff.
Example_
Check this.
xj3cbfub6#
I had a table with PartDesc column as below. Where I need to delete the characters starting from index 1 till '-'character.
| PartDesc |
| ------------ |
| OPERA_BLUE-ALTROZ DCA XZ 1.2 RTN BS6 |
| ATLAS_BLACK-NEXON XZ+ DK 1.2 RTN BS6 |
| DAYTONA_GREY-PUNCH ADV 1.2P BS6 MT RT |
| ARCADE_GREY-ALTROZ XZ+ 1.2 RTN BS6 |
| CALGARY_WHTE-NEXON XM(S) 1.2 RTN BS6 |
Here, after using the below query I got the desired result. Select PATINDEX('%-%',PartDesc),Stuff(PartDesc,1,PATINDEX('%-%',PartDesc),'' ),* from #temp