SQL 如何替换sql server中的第n个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28674797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace nth character in sql server
提问by Imran Zain
I am trying to replace the nth character in SQL Server. I tried with it using replace()
:
我正在尝试替换 SQL Server 中的第 n 个字符。我尝试使用它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.
在上面的代码中,所有的零都将被替换为一,但我只想在特定位置更改它,有时该位置可能会更改。
回答by Imran Ali Khan
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.
use stuff STUFF 函数将一个字符串插入到另一个字符串中。它在起始位置删除第一个字符串中指定长度的字符,然后将第二个字符串插入到起始位置的第一个字符串中。
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 pcnatefor suggestion) starting_index is your int position to replace.
“这里你要替换的 int 位置”是没有用任何 int 替换的位置,该位置将被替换 注意:(感谢pcnate的建议)starting_index 是你要替换的 int 位置。
回答by lc.
You're looking for STUFF
:
您正在寻找STUFF
:
select STUFF(ABC, @n, 1, 'X') from XXX
This would replace the @n
th character with an X
.
这会将@n
第 th 个字符替换为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.
从技术上讲,它ABC
从位置开始的列中查找原始字符串@n
,删除1
字符,然后'X'
在该位置插入字符串。
回答by asontu
回答by A_Sk
Use Stuff.
使用东西。
STUFF(Column_Name,starting_index,
lenth_ofthestring_to_replace_from_starting_index, character_to_replce)
Example_
例子_
DECLARE @str varchar(100) = '123456789'
select @str
SELECT STUFF(@str,2,1, 'hello')
-- want to replece 1 charter starting from 2nd position with the string 'hello'
Check this.
检查这个。
SELECT STUFF(@str,2,25, 'hello'),len(@str)