SQL Server - 创建自动递增唯一键
SQL Server 有没有办法创建一个主键自动递增的表?我一直在研究“UniqueIdentifier”类型,但这似乎没有达到我的预期。
目前,我有这样的事情:
CREATE TABLE [dbo].[MyTable](
[Date] [datetime] NOT NULL,
[MyField1] [nchar](50) NOT NULL,
[MyField2] [nvarchar](max) NULL,
[Key] [uniqueidentifier] NOT NULL
) ON [PRIMARY]
基本上,我希望 KEY 从 1 开始,并为每个记录增加自身。
Is there a way in SQL Server to create a table with a primary key that auto-increments itself? I've been looking at the "UniqueIdentifier" type, but this doesn't seem to do what I expect.
Currently, I have something like this:
CREATE TABLE [dbo].[MyTable](
[Date] [datetime] NOT NULL,
[MyField1] [nchar](50) NOT NULL,
[MyField2] [nvarchar](max) NULL,
[Key] [uniqueidentifier] NOT NULL
) ON [PRIMARY]
Basically, I want KEY to start at 1 and just increment itself for each record.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在查找 IDENTITY 属性 。
从文档中:
种子
增量
顺便说一句,所有这一切都可以通过 Sql Server 的管理 UI 轻松实现。只需右键单击您的表格并选择设计即可。然后选择适当的列并设置 IDENTITY 属性。
You're looking for the IDENTITY property.
From the documentation:
seed
increment
Btw, all of this is also easily achieved from Sql Server's mgmt UI. Just right click on your table and select design. Then select the proper column and set the IDENTITY property.
在表创建语句中定义主键,如下所示:
[Key] [int] IDENTITY(1,1) NOT NULL
Define your primary key in the table create statement like this:
[Key] [int] IDENTITY(1,1) NOT NULL