Total Pageviews

2013/12/05

How to pad a string with spaces when size of data is unknown in Microsoft SQL Server

Requirement
When I select a character data with varchar(6) from Microsoft SQL Server....

And these data should have fixed length in report.
If the data is 01, it should right pad with 4 spaces.
If the data is 01234, it should right pad with 1 space.

Solution
If we would like to meet this requirement in SQL Server, we can use 'CAST' function which provided by SQL Server
select cast(repno as char(6)) from NSS313FA  

Utilizing cast function in SQL statement, you can get fixed length in report no matter how long the data is.
   


No comments: