替换 SQL Server 2008 中的最后一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26647039/
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 02:53:16  来源:igfitidea点击:

Replace Last character in SQL Server 2008

sqlsql-serversql-server-2008

提问by Imran Ali Khan

I am working with SQL server 2008, and facing problem about character replacement.

我正在使用 SQL Server 2008,并面临有关字符替换的问题。

If I use

如果我使用

SELECT REPLACE(MYWORD,0,1) FROM MYTABLE

It is replacing all 0 into 1, I just want to replace Last character Like MYWORD = "ERMN0"so it will be MYWORD = "ERMN1"

它正在将所有 0 替换为 1,我只想替换最后一个字符 LikeMYWORD = "ERMN0"所以它会MYWORD = "ERMN1"

回答by Dan Field

using STUFF, which, IMO, ends up being most readable:

using STUFF,其中,IMO,最终是最易读的:

DECLARE @MyWORD VARCHAR(20) = 'ABCDEF123'

SELECT STUFF(@MyWORD, LEN(@MyWORD), 1, '2')

output:

输出:

ABCDEF122

回答by P?????

Try this.

尝试这个。

SELECT LEFT('ERMN0', Len('ERMN0')-1)
       + Replace(RIGHT('ERMN0', 1), 0, 1) 

OUTPUT : ERMN1

输出:ERMN1

In your case

在你的情况下

SELECT LEFT(MYWORD, Len(MYWORD)-1)
       + Replace(RIGHT(MYWORD, 1), 0, 1) as [REPLACED] FROM MYTABLE

回答by u500452

You may use combination of LEFT, RIGHT, and CASE.
You need to use CASEto check the most RIGHTcharacter whether it's a 0or not and replace it with 1. And at last, combine it with the LEFTpart (after being separated from the last character) of the MYWORDstring.

您可以使用的组合LEFTRIGHTCASE
您需要使用CASE来检查最多的RIGHT字符是否为 a0并将其替换为1. 最后,将其与字符串的LEFT部分(与最后一个字符分开后)组合MYWORD

However, depending on your requirement, it may have a drawback. When there is a word ending with 10, it would also be replaced.

但是,根据您的要求,它可能有缺点。当有一个以 结尾的词时10,它也会被替换。

SELECT LEFT(MYWORD,LEN(MYWORD)-1) + CASE RIGHT(MYWORD,1) WHEN '0' THEN '1' ELSE RIGHT(MYWORD,1) END

回答by Abhishek Jaiswal

this is also use full to replace letters from end

这也使用 full 来替换结尾的字母

It is used from replacing characters from end 1,2 or N

它用于替换结尾 1,2 或 N 的字符

 Declare @Name nvarchar(20) = 'Bollywood' 
select @Name = REPLACE(@Name, SUBSTRING(@Name, len(@Name) - 1, 2), 'as') 
SELECT @Name

output is "Bollywoas"

输出是“Bollywoas”

  • Here best part is you can repalce as many character from last you needed.
  • 这里最好的部分是你可以从你需要的最后一个角色中替换尽可能多的角色。

回答by Fred

This will work

这将工作

SELECT LEFT ('ERMN0' , Len('ERMN0') -1 ) + REPLACE(Right('ERMN0', 1), '0','1')

Or in your case

或者在你的情况下

SELECT LEFT (MYWORD , Len(MYWORD) -1 ) + REPLACE(Right(MYWORD, 1), '0','1') AS MYWORD FROM MYTABLE

回答by Imranullah Khan

Try this

尝试这个

SELECT SUBSTRING(MYWORD, 1, LEN(MYWORD) - 1) +
REPLACE(SUBSTRING(MYWORD, LEN(MYWORD), LEN(MYWORD)), 0, 1) FROM MYTABLE