Replace the last character in SQL Server 2008

I am working with SQL Server 2008 and am facing a character swap problem.

If i use

SELECT REPLACE(MYWORD,0,1) FROM MYTABLE 

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

+6
source share
6 answers

using STUFF , which, IMO, becomes the most readable:

 DECLARE @MyWORD VARCHAR(20) = 'ABCDEF123' SELECT STUFF(@MyWORD, LEN(@MyWORD), 1, '2') 

output:

 ABCDEF122 
+7
source

You can use a combination of LEFT , RIGHT and CASE .
You need to use CASE to check the RIGHT character itself, whether a 0 or not, and replace it with 1 . And finally, combine it with the LEFT part (after the branch from the last character) of the MYWORD string.

However, depending on your requirement, it may have a flaw. When there is a word ending in 10 , it will also be replaced.

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

Try it.

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

OUTPUT: ERMN1

In your case

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

It 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 
+1
source

try it

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

it is also used to replace letters from the end

Used to replace characters from the end of 1,2 or N

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

output of "Bollywoas"

  • Here, best of all, you can display as many characters as you need.
+1
source

Source: https://habr.com/ru/post/977458/


All Articles