SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

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

By Joshua A. Walker, 2009/03/05

Total article views: 1119 | Views in the last 30 days: 32

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]

By Joshua A. Walker, 2009/03/05

Total article views: 1119 | Views in the last 30 days: 32
Your response
 
 
Related tags

Administration     DBA    
data     Miscellaneous    
Data Warehousing     Warehouse    
 
 
Contribute
Like this? Try these...

Backup all DBs of a SQL-Server Instance

By hangg | Category: SQLServer
(not yet rated) | 1,334 reads

Free registration required...

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Login (existing users)

Login

Email:   Password:   Remember me: Forgotten your password?

Register (new users)

Register

Email:   Password:
Confirm:

Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

Steve Jones
Editor, SQLServerCentral.com