Pad a number with leading zeros in SQL to make uniform char length

When you are in need of transforming a number to have some character to be prefixed in order to make the chars in the number a specific number long, here is one way to do it.

commit f8394c6 · authored · 1 min read

Pad a number with leading zeros in SQL to make uniform char length

When you are in need of transforming a number to have zeros prefixed, use the below query. In order to prefix with zeros, we need to convert the number to a varchar.

SELECT REPLACE(STR(n,x),’ ’,‘y’)

STR function in SQL returns character data converted from numeric data. In the query, ‘n’ is the number to be transformed. ‘x’ is the number of chars to be returned and ‘y’ is the character to be prefixed with the number ‘n’ in order to make the specified length ‘x’.

eg. SELECT REPLACE(STR(9,5),’ ’,‘0’) will return “00009”

Additional Resources

local graph · open full graph

"Pad a number with leading zeros in SQL to make uniform char length" is connected to the topics SQL Server and related to 8 other entries. Style Guide - SQL Server Auditing Column Names Style Guide - SQL Server Au… SQL Server - Delete Duplicate Rows SQL Server - Delete Duplica… Dapper - Execute Multiple Stored Procedures Dapper - Execute Multiple S… Create SQL Server Database From a Script in Docker-Compose Create SQL Server Database … Microsoft SQL Server Guy Trying Oracle Database Microsoft SQL Server Guy Tr… Docker - SQL Error on ASP.NET Core Alpine Docker - SQL Error on ASP.N… Create New Database Level User Create New Database Level U… UTC to UAE Time (Arabian Standard Time) UTC to UAE Time (Arabian St… SQL Server #sql-server Pad a number with leading zeros i…

comments

loading discussion…