Solved

Format SQL 2005 View - add 6 zeros in front

Posted on 2014-10-16
2
135 Views
Last Modified: 2014-10-16
I have a SQL 2005 server and I have value that is a number. The number can be 1 or 2 or 3 digits maximum BUT I need the number to be 8 digits leading zeros for an export system.

Example:  
My numbers:
3
12
120

What I need in my sql view:  (notice it is 8 characters with leading zeros)
00000003
00000012
00000120

Here is my basic statement:
Select Invoices.InvoiceQuantity
FROM dbo.Invoices
0
Comment
Question by:allenkent
2 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
Comment Utility
No can do as a numeric data type, as they do not support leading zeros.

The only way to pull that off is to convert it to a char with leading zeros, and use RIGHT to handle the number of zeros correctly, in the set that displays it.
For a demo, copy-paste and execute the below into your SSMS
CREATE TABLE #tmp (numbers int) 

INSERT INTO #tmp (numbers) 
VALUES (3), (12), (120) 

SELECT RIGHT('00000000' + CAST(numbers as varchar(8)), 8) as my_number 
FROM #tmp

Open in new window

0
 

Author Closing Comment

by:allenkent
Comment Utility
PERFECT!
SELECT RIGHT('00000000' + CAST(numbers as varchar(8)), 8) as my_number
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Join & Write a Comment

I am showing a way to read/import the excel data in table using SQL server 2005... Suppose there is an Excel file "Book1" at location "C:\temp" with column "First Name" and "Last Name". Now to import this Excel data into the table, we will use…
In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now