Padding Success Using Microsoft .NET & TSQL

Padding is often a programmers best friend.  If you have ever worked with data then you have received different formats and different datatypes.  Whether it’s an integer field, char field, or nvarchar field, padding will help you format the results into a common length for consistent display or storage.

For example, you have a Member ID number that is stored as an integer, but for displaying in a report or an application you need to left pad with all zeros. Perhaps a business rule indicates it must be a certain length of numbers.

C# Example

A quick example to pad an Integer with zeros in C#:

C#
System.Int32 intMyInteger = 87366; 
System.String strMyInteger = intMyInteger.ToString().PadLeft(20, '0');

This example can be used for multiple scenarios, not just zeros.  There are two ways to pad in .NET.  PadLeft will concatenate leading characters with the supplied value.  PadRight will concatenate trailing characters with the supplied value.

VB.NET Example

A quick example to pad an Integer with zeros in VB.NET:

VB
Dim intMyInteger As System.Int32 = 87366
Dim strMyInteger As System.String = intMyInteger.ToString().PadLeft(20, "0"C)

T-SQL Example

A quick example to pad an integer with zeros in T-SQL:

SQL
SELECT RIGHT('00000000000000000000'+CAST(field AS VARCHAR(20)),20)

Like most everything in IT there are multiple ways to pad fields.

Scroll to Top