如何制作“无重复"SQL Server 2008 中的列?

2021-09-14 00:00:00 unique sql-server unique-constraint

我的 SQL Server 数据库中有一个简单的表.该表包含两列:ID int, Name nvarchar(50).ID 列是我的表的主键.

I have a simple table in my SQL Server database. This table contains two columns: ID int, Name nvarchar(50). The ID column is the primary key for my table.

我希望Name"列是(No Duplicates)",就像在 Microsoft Access 中一样,但此列不是主列.我怎么能这样做?

I want the "Name" column to be "(No Duplicates)", like in Microsoft Access, But this column isn't the primary column. How could I do this?

推荐答案

添加 该列的唯一约束:

ALTER TABLE Foo ADD CONSTRAINT UQ_Name UNIQUE (Name)

<小时>

通过 SQL Management Studio UI 添加:


To add it through SQL Management Studio UI:

  1. 打开 SQL Server Management Studio.
  2. 展开要在其中创建约束的数据库的 Tables 文件夹.
  3. 右键单击要添加约束的表,然后单击设计.
  4. 在表设计器中,点击索引/键.
  5. 点击添加.
  6. 在类型下拉列表中选择唯一键.
  1. Open SQL Server Management Studio.
  2. Expand the Tables folder of the database where you wish to create the constraint.
  3. Right-click the table where you wish to add the constraint and click Design.
  4. In Table Designer, click on Indexes/Keys.
  5. Click Add.
  6. Choose Unique Key in the Type drop-down list.

要处理发生唯一约束违反的情况,请参阅错误2601.

To handle a situation where a unique constraint violation occurs, see for error 2601.

相关文章