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?
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.
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.
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.
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.
One way to reliably and nicely do this:
ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric valueSo 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.
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