Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment primary key in SQL Server (long unique code)

I need add new column in to DB table but with auto increament (primary key). I could use this:

ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)

but this creates unique integers 1, 2, 3, etc But i would like create long uniques numbers exmpl: 0542365 or with letters A546980 it is posible?

like image 709
Klapsius Avatar asked Aug 21 '14 09:08

Klapsius


People also ask

Can Unique Key be set for auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How can change primary key to auto increment in SQL Server?

If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.

How do I change my primary key to auto increment?

To change a primary key to auto_increment, you can use MODIFY command. Let us first create a table. Look at the above sample output, StudentId column has been changed to auto_increment.

What is the syntax for auto increment in SQL?

You can also make an auto increment in SQL to start from another value with the following syntax: ALTER TABLE table_name AUTO_INCREMENT = start_value; In the syntax above: start_value: It is the value from where you want to begin the numbering.


1 Answers

One way to reliably and nicely do this:

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.YourTable
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   AlphaID AS 'A' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into YourTable without specifying values for ID or AlphaID:

INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and AlphaID will contain values like A0000001, A0000002,...... and so on - automatically, safely, reliably, no duplicates.

like image 150
marc_s Avatar answered Oct 21 '22 20:10

marc_s