Setting method: 1. Use the SQL Server Management Studio tool to connect to the database; 2. Expand "Table" in the database, right-click the data table that needs to be set, and select "Design"; 3. In the table designer interface, right-click the corresponding row and select "Set Primary Key" to complete the setting of the primary key and click Save.
The primary key is one or more fields in the table, and its value is used to uniquely identify a record in the table. In a relationship between two tables, the primary key is used in one table to reference a specific record from the other table. The primary key is a unique key that is part of the table definition. The primary key of a table can be composed of multiple keywords, and the columns of the primary key cannot contain null values.
Define the primary key
Open the [SQL Server Management Studio] management tool and connect to the database
Use the SSMS tool to define the primary key
Use SQL to define the primary key
Method 1: Define the primary key when creating the data table
USE schoolDB --打开数据库schoolDB GO IF EXISTS(SELECT * FROM sysobjects WHERE name='student') DROP TABLE student --检查student是否已经存在,如果存在,则删除 GO CREATE TABLE student --表名为student ( StuID int NOT NULL PRIMARY KEY, --学生学号 StuName varchar(15) NOT NULL, --学生姓名 Sex char(2) NULL, --性别 Major varchar(20) NULL, --所选专业 )
Method 2: Modify the data table definition primary key
USE schoolDB --打开数据库schoolDB GO ALTER TABLE student ADD CONSTRAINT PK_student PRIMARY KEY (StuID) --将表中的StuID设为主键
Delete primary key
Delete primary key using SSMS tool
Method 1: Delete the primary key in the Object Explorer
方式二:在表设计器中删除主键
使用SQL方式删除主键
在SSMS工具栏中单击“新建查询”,打开“SQL编辑器”窗口
输入创建SQL代码
USE schoolDB --打开数据库schoolDB GO ALTER TABLE student DROP CONSTRAINT PK_student --将表中的主键约束PK_studnet删除
The above is the detailed content of How to set primary key in sql database?. For more information, please follow other related articles on the PHP Chinese website!