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
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With