SQL Tip #13 – Padding a number with leading Zeros

Following SQL can be used in order to format a number with leading zeros.

The trick is to use STR function with REPLACE.

Character representation of a number can be achieved using STR function. If the result is less than specified length, then leading spaces are added. So next trick is to use REPLACE function to replace spaces with zeros.

DECLARE @number INT
DECLARE @leadingZero INT

SET @number = 123
SET @leadingZero = 10

SELECT REPLACE (STR( @number, @leadingZero ), ' ' , '0' )
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s