Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Management Studio ZEROFILL

I am trying to add a auto_increment primary key with ZEROFILL with a max size of six.

So it outputs:

000001
000002 etc...

However I am really struggling to achieve this and cant find the answer. How do I set up this column type in SQL Server Management Studio?

Thanks

like image 909
Austin Avatar asked Feb 27 '13 13:02

Austin


3 Answers

You cannot do this with an integer field in SQL Server (nor would I recommend it with a Varchar).

Let SQL Server store the field as an Identity, and then (assuming this is for display), format the data when you select it like such:

SELECT RIGHT('000000' + CONVERT(VARCHAR(6),ID), 6) FROM Table
like image 107
sgeddes Avatar answered Oct 11 '22 13:10

sgeddes


What you're trying to achieve is not possible. Display formatting is done in a presentation layer and not in the database. You need to separate a value from the presentation of a value. The two values 1 and 000001 are the same.

If you want to return something formatted, then you would have to return the value as a string. Just cast it to a string, add a number of zeroes at beginning and then keep the leftmost n characters.

like image 45
Yaroslav Avatar answered Oct 11 '22 15:10

Yaroslav


SELECT FORMAT(2, N'000000')
--OR
SELECT FORMAT(2, CAST(REPLICATE(0, 6) AS NVARCHAR(6)))

https://docs.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql?view=sql-server-ver15

like image 35
Alix Avatar answered Oct 11 '22 15:10

Alix