Replace non-numeric characters in a column by a number

Kabdar 1 Reputation point
2023-02-20T09:25:41.44+00:00

Hello,

I have a column(varchar) in my table that contains numbers but also strings. Is it possible to replace all non-numeric characters in this column by numbers? How to do that?

SQL Server Other
{count} votes

2 answers

Sort by: Most helpful
  1. LiHongMSFT-4306 31,566 Reputation points
    2023-02-21T02:18:24.93+00:00

    Hi @Kabdar

    If I guess right, you might try this solution using TRANSLATE function which is available on SQL Server 2017 (14.x) and later and also Azure SQL.

    Syntax: TRANSLATE (inputString,characters, translations)

    Here is a sample replaces any non-numeric characters with number 0:

    DECLARE @Temp_Table TABLE(Col VARCHAR(20))
    INSERT INTO @Temp_Table VALUES
    ('Ajs57uj9T'),('PH89Ths67'),('URT889hsy')
    SELECT TRANSLATE([Col], 'abcdefghijklmnopqrstuvwxyz+()- ,#+', '0000000000000000000000000000000000') AS New_Col
    FROM @Temp_Table
    

    Note that the character number of the two arguments characters and translations should be same. In the sample above, they both have 34 characters.

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. Zahid Butt 961 Reputation points
    2023-02-20T14:35:26.2166667+00:00

    Hi,

    Its better to send here perfect example, anyways you may try replace string function from below article:

    https://learn.microsoft.com/en-us/sql/t-sql/functions/replace-transact-sql?view=sql-server-ver16

    For example I have a varchar column in a table, I have used

    replace('nam 2002681','nam','123') to replace 'nam' with '123' in the string.

    Regards,

    0 comments No comments

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.