Select Query for the fixed length

happysmile picture happysmile · Oct 2, 2012 · Viewed 24.5k times · Source

I have an table called customer where i am selecting few columns and making its fixed length,where i need to send the values to SSIS packages for an fixed length output and is written in a text file

customerID:10
Mobilenumber:11
Emailaddress:256

select customerID,mobilenumber,Emailaddress from customer 

I want to make sure my customerID is always length of 10, mobile number 11, emailaddress 256.

Answer

Tim Lehner picture Tim Lehner · Oct 2, 2012

You can cast them as fixed-length string datatypes, as in:

select cast(customerID as char(10)) as customerID,
    cast(mobilenumber as char(11)) as mobilenumber,
    cast(Emailaddress as char(256)) as Emailaddress
from customer

If you come across any oddity while working like this, it may be helpful to keep your ANSI_PADDING settings in mind.

Another way to do this might be:

select left(Emailaddress + replicate(' ', 256), 256)

Though this method is often just to apply similar logic from other languages to T-SQL.