Thursday, 15 September 2011

tsql - Convert varchar to 3 (sometimes 4) chars in T-SQL -


I select the data from the database. The value is (the name of the field is ADR_KOMP_VL):

  4, 61a, 100, 12, 58, 123C, 6A, 5   

Required

  004, 061a, 100, 012, 3, 0, 1, 2, 3, 2, 3, 4, 0, 058, 123C, 006A, 005.  

The rules are:

  • always 3 digits
  • no location
  • If the original value is less than three digits, So keep it in front of 0. (Length is 3)
  • If the original value has one letter, keep it in front of 0 (but length 4)

    I have a "no space" portion This is:

      Select REPLACE (ADR_KOMP_VL, '', '')    is the solution yet:  
     < Code> SELECT RIGHT ('000' + CONVERT (VARCHAR (4)), REPLACE (ADR_KOMP_VL, '', '')), 3)   

    but it only gives me the correct length , When my value is in the value no my problem is how to handle values ​​with a letter in them ??

    You can use a case statement:

      SELECT ('0000' + VCHAR (4), Replace (ADR_COMVVVL, '', '')), 4) Other rights ('000' + converter (VARCHAR) (4), REPLACE (ADR_KOMP_VL, '', '')), 3) end)    

No comments:

Post a Comment