how to format string/number (1 to 0001)

  • hi there, anyone can help formating string/number like

    string 1 to 0001

    string 2 to 0002

    etc

    thx b4

  • Here are a couple of way to do it:

    select
     M1 = right(1000000+MyNumber,4) ,
     M2 = right('0000'+convert(varchar(20),MyNumber),4)
    from
     (
     select MyNumber=1 union all
     select 10 union all
     select 44 union all
     select 7777 union all
     select 9999 union all
     select 111
     ) a
    Results:
    M1   M2   
    ---- ---- 
    0001 0001
    0010 0010
    0044 0044
    7777 7777
    9999 9999
    0111 0111
    (6 row(s) affected)
    
     
  • many thx michael!

  • Thought I'd add one... see "M3"...

    select

      M1 = right(1000000+MyNumber,4) ,

      M2 = right('0000'+convert(varchar(20),MyNumber),4),

      M3 = REPLACE(STR(MyNumber,4),' ','0')

    from

      (

      select MyNumber=1 union all

      select 10 union all

      select 44 union all

      select 7777 union all

      select 9999 union all

      select 111

      ) a

     

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

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply