help in writing update sql query

Heisenberg 261 Reputation points
2021-08-25T17:19:37.29+00:00

i want to write an update statement that has numbers, its a varchar datatype. I want to replace each occurrence of a number with different number. For ex. 0 will be replaced by 1, 1 will be replaced by 5 , 2 will be replaed by 7 and so on.

So if a row with value of 012, should be updated to 157.

Can someone help me write an update for this, it has to be an efficient update statement as i have a large number of rows to be updated.

Developer technologies Transact-SQL
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-08-25T20:52:52.003+00:00

    For your previous example that does not work, check an alternative:

    select replace(replace(replace(replace(replace(replace(replace(replace(
        '01234516',
        '0', char(6+16)),
        '1', char(8+16)),
        '2', char(7+16)), 
        '6', char(9+16)),
        char(6+16), '6'),
        char(8+16), '8'),
        char(7+16), '7'), 
        char(9+16), '9')
        AS Replaced
    
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. Heisenberg 261 Reputation points
    2021-08-26T15:37:31.923+00:00

    Viorel,
    Thanks for the answer, seems like it is working perfectly, can you explain the logic behind this? also let me know how can i be good in writing logic this just like you :)

    EchoLiu-msft , your logic is not working if i ve a number like this 69234516.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.