• Jeff, your "auto magic" one came the closest but I got some extra zeros I haven't quite figured yet -

    Original Modified

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

    A14 A00014

    B2 B0002

    OBT 0000OBT

    YH3 YH0003

    XX 0000XX

    So - too many zeroes, the whole string must be 4. And if there was no digit found it puts the zeros at the beginning of the string rather than after the letters.

    Yes... in my first attempt, that's what happens... did you try the second attempt? For your convenience, here it is again...

    --===== 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' UNION ALL

    SELECT 'A' UNION ALL

    SELECT '' UNION ALL

    SELECT 'A14' UNION ALL

    SELECT 'B2' UNION ALL

    SELECT 'OBT' UNION ALL

    SELECT 'YH3' UNION ALL

    SELECT 'XX'

    --===== 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(

    REPLICATE('0',@MaxWidth)

    + SUBSTRING(d.String,d.LastLetter+1,@MaxWidth)

    , @MaxWidth-d.LastLetter)

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

    SELECT String,

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

    FROM @TestData

    )d

    --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)