Thursday 5 November 2009

Beautiful Code - Trailing zeros

Sometimes during the course of a day you come across something that makes you see how beautiful programming can be.

For example I was looking for a way of adding trailing zeros to a string however the string was variable length between one and five characters long and had to be a total of six characters long. Adding a set number of zeros wouldn't work because the variable length of string.

After a bit of searching I found the following beautiful code:

UPDATE SomeTable
SET SomeColumn = LEFT(SomeColumn + '000000', 6)

This code sets SomeColumn to be atleast 6 characters long by concatenating SomeColumn with six zeros. Then you chop off all characters except the first six characters using 'left' and you have the correctly formatted result string.

I think this is a beautiful way of adding trailing zeros to a string.

Please share your beautiful code

1 comment: - Vận tải Con thoi said...

Thanks for sharing.
Nếu cần vận chuyển hàng đi nha trang thì a/c liên hệ bên mình nhé.
Hotline: 0903751981