Search code examples
sql-servert-sqlsplitquotesalphanumeric

Add quotes around alpha characters in alphanumeric strings using T-SQL?


I want to add quotes around alphabets in an alphanumeric string. For eg: If my string is 8AB8973, the output expected is 8'AB'8973. There is no specific pattern in which the numbers and characters will occur. I tried to run the following piece of code I found on StackOverflow, but it adds a space between numbers and alphabets, when I try to replace the space with quotes, the query takes forever to run.

    DECLARE @position INT;
    DECLARE @string VARCHAR(max);

    SET @string = '9FX8173'

    WHILE 1 = 1
      BEGIN
          SET @position = (SELECT Min(position)
                           FROM   (VALUES (Patindex('%[^ 0-9][0-9]%', @string)),
                                          (Patindex('%[0-9][^ 0-9]%', @string))) AS T(position)
                           WHERE  T.position > 0);

          IF @position IS NULL
            BREAK;

          SET @string = Stuff(@string, @position + 1, 0, ' ');
       END

       PRINT @string

Solution

  • In addition to replacing space with a quote in the STUFF function, you need to do the same in the PATINDEX search expressions:

    DECLARE @position INT;
    DECLARE @string VARCHAR(max);
    
    SET @string = '9FX8173';
    
    WHILE 1 = 1
    BEGIN
        SET @position = (
            SELECT MIN(position)
            FROM (VALUES (PATINDEX('%[^''0-9][0-9]%', @string)),
                         (PATINDEX('%[0-9][^''0-9]%', @string))) AS T(position)
            WHERE  T.position > 0);
    
        IF @position IS NULL
            BREAK;
    
        SET @string = STUFF(@string, @position + 1, 0, '''');
    END
    
    PRINT @string;