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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:19:51  来源:igfitidea点击:

How to replace nth character in sql server

sqlsql-serversql-server-2008

提问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 @nth character with an X.

这会将@n第 th 个字符替换为X.

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

从技术上讲,它ABC从位置开始的列中查找原始字符串@n,删除1字符,然后'X'在该位置插入字符串。

回答by asontu

You use STUFFfor this:

STUFF用于此:

SELECT STUFF(ABC, 5, 1, '1')
FROM XXX

This would replace the 5th character with a 1.

这会将第 5 个字符替换为 1。

回答by Gordon Linoff

Use stuff():

使用stuff()

select stuff(abc, 0, 1, 'a')

It is documented here.

它记录在此处

回答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)