How to Stuff the positions with blanks?

  • Hi ...
    I got a format to fill the positions to create a long string.

    Pos. Name Attribute
    1-3 Transaction 123
    4-6 Number 567
    7-12 Loan Number *
    13-41 Filler  
    42-48 Interest  LZF, +/-
    49-89 Filler2  
    90-102 Expanded acct Number '000' & accountnumber with leading zeros

    So,
    I am having something like this 
    SELECT '123567*' + Space(41-8)+ cast(ltrim(rtrim(Interest)) as varchar (7))+  Space(89-49) + '000'+ '0000123456' as String

    Issue here is interest is not 7 characters every time , it can be 4 or 5 . If it is 5 characters how to fill the rest 2 characters ?
    Example of Interest :
    345.6
    1234.56
    890.34

  • SELECT '123567*' + Space(41-8)+ left(cast(ltrim(rtrim(Interest)) as varchar (7)) + Space(6), 7)+ Space(89-49) + '000'+ '0000123456' as String

    SQL DBA,SQL Server MVP(07, 08, 09) "Money can't buy you happiness." Maybe so, but it can make your unhappiness a LOT more comfortable!

  • Casting things to CHAR will force a specific length, so something a bit like:
    Select
     Cast(trans As Char(3))
     +Cast(Number As Char(3))
     +Cast(Loan As Char(6))
     +Space(41-13+1)
     +Cast(Interest As Char(7))
     +Space(89-49+1)
     +Right(Replicate('0', 100) + Cast(Acc As VarChar(10)), 102-90+1)
    From (Values
    (123,567,'*',345.6,34565),
    (123,567,'*',1234.56,34565),
    (123,567,'*',890.34,34565)
    ) D(Trans, Number, Loan, Interest, Acc)

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

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