• ...or, perhaps, something a bit more "auto-magic"... 😀

    --===== This just creates demonstrable test data and is NOT part of the solution

    SET NOCOUNT ON

    DECLARE @TestData TABLE(String VARCHAR(10))

    INSERT INTO @TestData (String)

    SELECT 'A012' UNION ALL

    SELECT 'A12' UNION ALL

    SELECT '12' UNION ALL

    SELECT '1' UNION ALL

    SELECT 'AB12' UNION ALL

    SELECT 'AB2'

    --===== This is the solution for the known constraints on the data as posted

    DECLARE @MaxWidth TINYINT

    SET @MaxWidth = (SELECT MAX(LEN(String)) FROM @TestData)

    SELECT Original = String,

    Modified = LEFT(d.String,d.LastLetter)

    + RIGHT('0000'+SUBSTRING(d.String,d.FirstDigit,4),@MaxWidth-d.LastLetter)

    FROM (--==== Derived table "d" finds the interface between letters/digits

    SELECT String,

    LastLetter = PATINDEX('%[a-z][0-9]%',String),

    FirstDigit = PATINDEX('%[0-9]%',String)

    FROM @TestData

    )d

    RESULTS:

    ========

    Original Modified

    ---------- ------------------

    A012 A012

    A12 A012

    12 0012

    1 0001

    AB12 AB12

    AB2 AB02

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)