Sql-server – Produce fixed length output to file regardless of the length of data in each column/row

sql serversql-server-2008

Not sure about this as I'm kind new to this.
I need to output rows to fixed length files format.

The table's columns are ID, Name & Desc. The output should be the same length for each row regardless of the data length. Name in one row can be 5 chars and another can be 7 but in the end the file output should be 15.

So I believe the idea would be, I'll define the output length for each column and then output the column data and fill the difference between the data and the column length with ' '(spaces).

Not sure how to do that. I've read about rpad but it requires you know the length of the column date which is unknown to me.

Best Answer

The select below will add the spaces required for each field. The date format is fixed to 10 characters. The "|" sign is was added to show that the size of each coloum is fixed. Can be removed if not needed.

SELECT LEFT(AccountCode + SPACE(20) , 20) +
'|' + LEFT(AccountName + SPACE(50) , 50)  +
'|' + LEFT((CAST(Account_Id AS NVarchar(10)) +
SPACE(10)), 10) + '|'+  
FORMAT(LastPayDate , 'yyyy-MM-dd')
FROM [Accounts]