[英]How do I Create an AutoCounter Column in a Table in SQL 2008 R2?
There is nothing in the "Data Type" drop-down that indicates an auto-counter. “数据类型”下拉列表中没有任何内容表示自动计数器。
I selected int
and I am assuming there is a setting somewhere else to turn it into an auto-counter. 我选择了int
,我假设在其他地方有一个设置将它变成一个自动计数器。
The idea is to have a 100% unique ID for my primary key, and every time a row is added it gets the next available ID number assigned to it. 我的想法是为我的主键提供100%唯一ID,每次添加一行时,它都会获得分配给它的下一个可用ID号。
http://img64.imageshack.us/img64/2472/primarykey.png http://img64.imageshack.us/img64/2472/primarykey.png
What you're after is called IDENTITY in SQL Server terminology. 你所追求的是在SQL Server术语中称为IDENTITY。
The column must be a numeric data type ( INT typically, check the range of values to what suits your needs ) before you can set the column to be IDENTITY
-- you can see the listing in your screenshot, under Table Designer . 该列必须是数字数据类型( 通常是INT,请检查适合您需要的值的范围 ),然后才能将列设置为IDENTITY
- 您可以在表设计器下的屏幕截图中看到列表。 There can only be one IDENTITY column per table -- this will change in SQL Server 2011 when they start support of sequences. 每个表只能有一个IDENTITY列 - 当它们开始支持序列时,它将在SQL Server 2011中更改。
CREATE TABLE dbo.mytable
(
[MY_ID] int identity (1,1) PRIMARY KEY CLUSTERED NOT NULL,
[LAST_NAME] [nvarchar](50) NULL,
[FIRST_NAME] [nvarchar](30) NULL
)
Of course if it isn't the primary key, you don't need the primary key clustered part. 当然,如果它不是主键,则不需要主键群集部分。
The (1,1) part indicates that the numbering will start at 1 and increment by 1. Do not expect identities to never have gaps though. (1,1)部分表示编号将从1开始并递增1.不要指望身份永远不会有间隙。 If an insert is rolled back or a record is deleted later, the gaps will not be filled in. You also can start at any number you chose and you can even increment in a different number but (1,1) is the default and is the most common value. 如果回滚插件或稍后删除记录,则不会填写间隙。您也可以从您选择的任何数字开始,甚至可以增加不同的数字,但(1,1)是默认值,并且最常见的价值。
It is best to create tables (and especially alter them) using scripts, then you can commit them to source control like any other code and you have them ready to deploy. 最好使用脚本创建表(尤其是更改它们),然后您可以像任何其他代码一样将它们提交到源代码控制,并准备好部署它们。
Mark it as a Primary key and set the Identity column to yes. 将其标记为主键并将Identity列设置为yes。 This will make it auto-increment. 这将使其自动增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.