Left-Padding Zeroes
- Get link
- X
- Other Apps
I recently ran across a case where a time value was stored as an Int, with the idea that the first two numbers are the hours, second two the minutes, and third two the seconds. This is all well and good if the hours are double digits (e.g. 144415), as you can just split the string every two characters. If the hours are single digit (e.g. 93251) doing that won't give you the right result. You'll wind up splitting out "93", "25", 1" when what you really want is "09", "32", "51". You also run into this stuff sometimes when you're trying to left-pad a string for a year, month, or date to a pretty format. None of these cases are particularly compelling, and there are probably other solutions for these sorts of issues, but what I DO want to share with you, is a couple ways you can left-pad a string with characters.
FWIW, I've tried doing left-padding with the FORMAT function, and maybe I just suck with it, but I haven't found a way I can pass it a format string with will left-pad zeroes. So without further adieu, here are a couple ways I found to left-pad integers. The same applies for strings as well, I just wanted to draw attention to the integer case.
declare @IntTime int = 84833 select -- Generate n zeroes, where n is the maximum length of the desired string. In this case, 6. The concatenate @IntTime (making a string of length n + len(@IntTime), where n is the desired total length) -- Then take the right n characters. This will grab however many characters are in @IntTime, left padded with the remaining zerose. right(replicate('0', 6) + cast(@IntTime as varchar(6)), 6), -- Use the rarely useful STR() function to left-pad @IntTime with n spaces (You MUST pass n explicitly otherwise STR() uses a default number of spaces). -- Then replace all the spaces with the character you want to fill with. -- Note, this won't work if the value you're padding contains spaces (i.e. if it's a string) replace(str(@IntTime, 6), ' ', '0'), -- Concatenate n - len(@IntTime) zeroes before @IntTime concat(replicate('0', 6 - len(@IntTime)), @IntTime)
Comments
Post a Comment