如何自动增加SQL Server数据库表中的主键?我已经通过论坛看了一下,但不知道如何做到这一点。

我看了房子的属性,但找不到选项。我看到了一个答案,你去到身份规范属性,并将其设置为“是”,并将身份增量设置为1,但该部分是灰色的,我不能将“否”更改为“是”。

一定有一个简单的方法来做到这一点,但我找不到。


当前回答

您可以执行以下操作:新建表:

-- create new table with Column ID which is Primary Key and Auto Increment --
    
CREATE TABLE titles(
      id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,  --Primary Key with Auto-Increment --
      keyword        VARCHAR(260),
      status VARCHAR(10),
 );

如果你的表已经存在,并且需要对ID列进行自动递增和主键的更改,那么请参见下面的内容:

ALTER TABLE table DROP COLUMN id; // drop the existing ID in the table 
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key

其他回答

您可以执行以下操作:新建表:

-- create new table with Column ID which is Primary Key and Auto Increment --
    
CREATE TABLE titles(
      id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,  --Primary Key with Auto-Increment --
      keyword        VARCHAR(260),
      status VARCHAR(10),
 );

如果你的表已经存在,并且需要对ID列进行自动递增和主键的更改,那么请参见下面的内容:

ALTER TABLE table DROP COLUMN id; // drop the existing ID in the table 
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key

您必须展开Identity部分以公开增量和种子。

编辑:我假设您的数据类型是整数,而不是char(10)。当我发布这个答案时,我想说哪个是合理的和有效的

在创建表时,可以使用关键字IDENTITY和PRIMARY KEY约束作为列的数据类型。 例:

StudentNumber IDENTITY(1,1) PRIMARY KEY

这里的第一个‘1’表示起始值,第二个‘1’表示递增值。

CREATE TABLE Persons (
    Personid int IDENTITY(1,1) PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);

MS SQL Server使用IDENTITY关键字执行自动增量特性。

在上面的例子中,IDENTITY的起始值是1,每增加一条新记录,它都会加1。

提示:要指定“Personid”列应该从值10开始,并增加5,请将其更改为IDENTITY(10,5)。

要向"Persons"表中插入一条新记录,我们不需要为"Personid"列指定一个值(一个唯一的值会自动添加):

确保Key列的数据类型是int,然后手动设置identity,如图所示

或者只运行这段代码

-- 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)

如果ID不是表中唯一的列,代码将运行

图像引用先进先出