Monday, February 4, 2013

SQL code snippets - Left padding a character

So I have accumulated a bunch of sql code snippets and tricks in my time as a developer, and I figured I could share some of the more useful ones.

If you ever wanted to be able to pad characters quickly in sql, here is some code for that.  Padding characters is when you want to take some arbitrary sized value, and "pad" or add characters to that value.  The following will add padding on the left of a string value.

/*
Two methods for padding a character, they both assume left padding.
*/
 
SELECT RIGHT(Replicate(@padchar, @len) + @str, @len) 

SELECT Stuff(@str, 1, 0, Replicate('0', @n - Len(@str))) 



select right(replicate('0', 10) + 'four', 10)
select stuff('four', 1, 0, replicate('0', 10 - len('four')))

Produces 000000four and 000000four as the output. 

No comments:

Post a Comment