Thursday, 18 June 2009

Padding a String With a Zero (0)

I constantly had the problem that I needed to use DATEPART to create filenames and other customized strings from dates. The problem is that DATEPART(mm,GETDATE()) will return the following results:
  • 1 for January
  • 2 for February
  • 3 for March
instead of 01 for January, etc.

So, for the purposes of sorting files by dates it is no good. In order to pad the datepart with a leading zero you need to use the RIGHT command. It's defined in BOL as:
Is an expression of character or binary data. character_expression can be a constant, variable, or column. character_expression can be of any data type, except text or ntext, that can be implicitly converted to varchar or nvarchar. Otherwise, use the CAST function to explicitly convert character_expression.

Is a positive integer that specifies how many characters of the character_expression will be returned. If integer_expression is negative, an error is returned. integer_expression can be of type bigint.

An example for my DATEPART predicament is as follows:
It's a good idea to convert the DATEPART from an integer to a string (though the RIGHT command does implicitly convert to a string). Limit it to two characters in length and by specifying a that you use 2 of the expression's characters makes sure that you don't add the leading zero to the months/days above 9. Make sense?

For a more generic example that I found on:
Obviously, if you need trailing zeroes you can use the LEFT command. It works in the same way.

No comments: