How to set a unique constraint in SQL Server?

In SQL Server, you can use the CREATE TABLE statement to establish a unique constraint. This constraint ensures that all values in a column (or a combination of columns) are unique. Here is an example:

CREATE TABLE 表名 (

    列名1 数据类型 CONSTRAINT 约束名 UNIQUE,

    列名2 数据类型,

    … );

In this case, “table name” is the name of the table to be created, “column name 1” is the name of the column to set a unique constraint, “data type” is the data type of the column, “constraint name” is the name of the constraint, and “UNIQUE” specifies it as a unique constraint. If you want to add a unique constraint to an already existing table, you can use the ALTER TABLE statement.

ALTER TABLE 表名 ADD CONSTRAINT 约束名 UNIQUE (列名1, 列名2, …);

Please note that the constraint name can be changed as needed to ensure uniqueness. Additionally, you can use the PRIMARY KEY keyword in the CREATE TABLE or ALTER TABLE statement to set a primary key constraint, which will also automatically create a unique constraint.

CREATE TABLE 表名 (

    列名 数据类型 PRIMARY KEY,

    … ); 或 ALTER TABLE 表名 ADD CONSTRAINT 约束名 PRIMARY KEY (列名);

The above is the way to set a unique constraint at the table level. If you want to set a unique constraint at the column level, you can use the UNIQUE keyword in the column definition.

CREATE TABLE 表名 (

    列名1 数据类型 UNIQUE,

    列名2 数据类型,

    … );

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds