sexta-feira, 12 de julho de 2013

SQL Server - Adding Leading Zeros

Well, sometimes you need to do some query in a numeric field and you need to add leading zeros for formatation purpose.

It's prety easy to do this! Take a look in the following query:

You'll use 'REPLICATE' to do the work here!

REPLICATE ( string_expression ,integer_expression ) 

Where string_expression is the string you want to replicate and integer_expression is the amount of times o want to replicate string_expression.

In my example:
string_expression: '0'. Wich means I want to replicate '0'.
integer_expression: 4 - LEN(CAST(id_user as varchar))).  I subtract id_user's length from the amount of times that I want to replicate '0'.

And in the end I concatenate the result of REPLICATE function with the field I did all the work.


This is the example without REPLICATE:

This will be the result with REPLICATE:


Nenhum comentário:

Postar um comentário