Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Function to Add Leading 0's (Zeros) to an INT

By Joshua A. Walker,

Copy the code. Run the create and there is test script in the comments section you can use for testing.

There is a line commmented out that will limit the maximum size to 100 characters.

 

EX: SELECT dbo.DBA_fnAddLeadingZeros(1234,6)

will return '001234' for a TOTAL length of 6 characters.

 

This is especially helpful in data warehousing where you want to force all numbers to a fixed length such as day = '01' instead of 1... etc...

 

SELECT dbo.DBA_fnAddLeadingZeros(DATEPART(MONTH,GETDATE()),2) [MONTH]
, dbo.DBA_fnAddLeadingZeros(DATEPART(DAY,GETDATE()),2) [DAY]
, DATEPART(YEAR,GETDATE()) [YEAR]
, dbo.DBA_fnAddLeadingZeros(DATEPART(MONTH,GETDATE()),2) [HOUR]
, dbo.DBA_fnAddLeadingZeros(DATEPART(MINUTE,GETDATE()),2) [MINUTE]
, dbo.DBA_fnAddLeadingZeros(DATEPART(SECOND,GETDATE()),2) [SECOND]

Total article views: 1573 | Views in the last 30 days: 1
 
Related Articles
FORUM

Issue with trying to incorporate the following SELECT DATEPART(WEEKDAY, GETDATE())

Issue with trying to incorporate the following SELECT DATEPART(WEEKDAY, GETDATE())

FORUM

DatePart

Show rolling future 12 months

FORUM

Datepart (mm, '01/01/2009') -1

Can I use datepart(mm, ...) to get months from previous year

FORUM

Getting datepart to work for query

Datepart function

FORUM

Getdate and Datepart

Hello All, I'm looking for options on using getdate. What I'm trying to get from getdate () is 01-...

Tags
administration    
data    
data warehousing    
dba    
miscellaneous    
warehouse    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones