Formatting numbers by padding with leading zeros in sql server

636    Asked by DavidWHITE in QA Testing , Asked on Jul 10, 2021

 We have an old SQL table that was used by SQL Server 2000 for close to 10 years.

In it, our employee badge numbers are stored as char(6) from 000001 to 999999.

I am writing a web application now, and I need to store employee badge numbers.

In my new table, I could take the short cut and copy the old table, but I am hoping for better data transfer, smaller size, etc, by simply storing the int values from 1 to 999999.

In C#, I can quickly format an int value for the badge number using

public static string GetBadgeString(int badgeNum) {
  return string.Format("{0:000000}", badgeNum);
  // alternate
  // return string.Format("{0:d6}", badgeNum);
}

How would I modify this simple SQL query to format the returned value as well?

SELECT EmployeeID
FROM dbo.RequestItems
WHERE ID=0

How to add leading zeros in sql?

Answered by Hellen Cargill

 Try changing the number 6 to the total required length:

  SELECT REPLICATE('0',6-LEN(EmployeeId)) + EmployeeId

But, if the column is defined as an INT, use RTRIM to implicitly convert it to the VARCHAR like this:

SELECT REPLICATE('0',6-LEN(RTRIM(EmployeeId))) + RTRIM(EmployeeId)
To remove the 0s and to get back the 'real' number, you can refer to below code:
SELECT RIGHT(EmployeeId,(LEN(EmployeeId) - PATINDEX('%[^0]%',EmployeeId)) + 1)

Your Answer

Interviews

Parent Categories