Friday, July 6, 2012

Padding zeros (0) in front of number or numerical string in T-SQL

To skip story start from the START:
I had to create a Alternate ID from the Employee ID in the following format
ABCD00000
4 characters followed by 5 digits. Employee ID was 4 or 5 digit so would have to pad 0 if 4 digits. I used STR combined with REPLACE function to do this.

START:
Syntax
STR (expression [, length [, decimal] ] )

Return type: varchar

expression: numerical vaue (numerical string would work too)
length: Length of resulting string including - + sign, decimal and digits
decimal: digits after decimal

REPLACE(string, pattern, replacement)

Return type: nvarchar or varchar
string: where you want to replace
pattern: what you want to replace
replacement: string to replace with

Example:

SELECT REPLACE(STR(123.45,10,4), ' ', '0')
SELECT REPLACE(STR('123.45',10,4), ' ', '0')
Result:
00123.4500


SELECT REPLACE(STR(123.45,10,0), ' ', '0')
SELECT REPLACE(STR('123.45',10,0), ' ', '0')
Result:
0000000123


SELECT REPLACE(STR(12345,10,0), ' ', '0')
SELECT REPLACE(STR('12345',10,0), ' ', '0')
Result:
0000012345


Astu...


No comments: