SQL Server auto increment a column without primary key

前端 未结 2 1473
感动是毒
感动是毒 2021-01-04 03:53

Is it possible to auto increment a column in SQL Server WITHOUT it being a primary key?

If yes how can this be done.

Thanks

相关标签:
2条回答
  • 2021-01-04 04:35

    Declare the column with the IDENTITY keyword, and simply do not create a PRIMARY KEY constraint on it.

    0 讨论(0)
  • 2021-01-04 04:51

    Yes. There is no requirement that IDENTITY columns be made a primary key.

    CREATE TABLE T
    (
    X INT PRIMARY KEY,
    Y INT IDENTITY(1,1)
    )
    

    Though I'm not sure when this would be useful. If you have a natural key that you want to use as the PK then you would probably want to put a unique constraint on the surrogate alternate key anyway.

    For purposes of setting up FK relationships SQL Server doesn't care if the column(s) is the PK or not it just requires a unique index on it/them.

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