auto incrementing id in sql server

梦想的初衷 提交于 2019-12-24 21:19:49

问题


How to auto increment an id in SQL Server whenever a new row is inserted in the table? This id is primary key of the table.


回答1:


You're looking for IDENTITY.

e.g.

CREATE TABLE MyTable
(
ID INTEGER IDENTITY(1,1) PRIMARY KEY,
FieldA VARCHAR(10)
)

The ID field will auto increment, starting at 1 and increasing by one each time.




回答2:


And to return the id in your code lookup scope_identity() and the OUTPUT clause. De not use @@identity as it can return the wrong value if triggers are put on the table, therefore it is not safe to use if you value data integrity.



来源:https://stackoverflow.com/questions/2771709/auto-incrementing-id-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!