Auto increment primary key in SQL Server Management Studio 2012

前端 未结 11 1043
谎友^
谎友^ 2020-11-22 10:11

How do I auto increment the primary key in a SQL Server database table, I\'ve had a look through the forum but can\'t see how.

相关标签:
11条回答
  • 2020-11-22 10:55

    Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?

    Example:

    CREATE SCHEMA blah.
    GO
    
    CREATE SEQUENCE blah.blahsequence
    START WITH 1
    INCREMENT BY 1
    NO CYCLE;
    
    CREATE TABLE blah.de_blah_blah
    (numbers bigint PRIMARY KEY NOT NULL
    ......etc
    

    When referencing the squence in say an INSERT command just use:

    NEXT VALUE FOR blah.blahsequence
    

    More information and options for SEQUENCE

    0 讨论(0)
  • 2020-11-22 10:59

    You can use the keyword IDENTITY as the data type to the column along with PRIMARY KEY constraint when creating the table.
    ex:

    StudentNumber IDENTITY(1,1) PRIMARY KEY
    

    In here the first '1' means the starting value and the second '1' is the incrementing value.

    0 讨论(0)
  • 2020-11-22 11:04

    When you're using Data Type: int you can select the row which you want to get autoincremented and go to the column properties tag. There you can set the identity to 'yes'. The starting value for autoincrement can also be edited there. Hope I could help ;)

    0 讨论(0)
  • 2020-11-22 11:05

    Make sure that the Key column's datatype is int and then setting identity manually, as image shows

    enter image description here

    Or just run this code

    -- ID is the name of the  [to be] identity column
    ALTER TABLE [yourTable] DROP COLUMN ID 
    ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)
    

    the code will run, if ID is not the only column in the table

    image reference fifo's

    0 讨论(0)
  • 2020-11-22 11:05

    If the table is already populated it is not possible to change a column to IDENTITY column or convert it to non IDENTITY column. You would need to export all the data out then you can change column type to IDENTITY or vice versa and then import data back. I know it is painful process but I believe there is no alternative except for using sequence as mentioned in this post.

    0 讨论(0)
提交回复
热议问题