简体   繁体   English

如何使用约束对话框向SQL Server 2008添加约束?

[英]How to add constraint to SQL Server 2008 using constraint dialog?

How do you manually define a constraint in SQL Server 2008 dialog box? 如何在SQL Server 2008对话框中手动定义约束? I want to add a constraint that when I add a new record if its already there don't add it. 我想添加一个约束,当我添加新记录时,如果它已经没有添加它。 My table is structured so that 我的表格结构如此

AdvCatJoinID is my primary key, CatID is the key from the Category table, and AliasID is the primary key from the alias table, I want the constraint to be that if the CatID and AliasID already exist in the table as a pair then don't add a new record (as it already exists), how to? AdvCatJoinID是我的主键, CatIDCategory表中的键, CatID是别AliasID中的主键,我希望约束是如果表中已经存在CatIDAliasID作为一对,那么就不要添加新记录(因为它已经存在),如何?

Thanks 谢谢

Do you really need the AdvCatJoinID column? 你真的需要AdvCatJoinID专栏吗? Usually for these association tables I just have a composite primary key on the 2 foreign key columns. 通常对于这些关联表,我只在2个外键列上有一个复合主键。 That enforces the unique aspect. 这强制了独特的方面。

Otherwise to do it in SSMS you need to go through the "Indexes/Keys" dialogue (NOT the constraints one) and configure a new Unique Index with both columns selected. 否则,要在SSMS中执行此操作,您需要通过“索引/键”对话框(而不是约束条件)并配置一个新的唯一索引,并选择两个列。 You access this dialogue after right clicking the table and selecting "Design" then right clicking the table designer grid. 右键单击表并选择“设计”然后右键单击表设计器网格后,可以访问此对话框。

To create a unique constraint rather than unique index you would choose the option "Unique Key" but there is no practical difference netween the two. 要创建唯一约束而不是唯一索引,您可以选择“唯一键”选项,但两者之间没有实际区别。

Step 1: 步骤1:

In the SQL Server Object Explorer, find your database and table that you want to put the constraint on, and navigate to the Indexes subnode, and right-click, choose New Index : 在SQL Server对象资源管理器中,找到要放置约束的数据库和表,然后导航到Indexes子节点,右键单击,选择New Index

在此输入图像描述

Step 2: 第2步:

In the dialog box that pops up, define your unique index: 在弹出的对话框中,定义您的唯一索引:

  • give it a name of your choosing 给它一个你选择的名字
  • make sure the [ X ] Unique checkbox is checked 确保选中[ X ] Unique复选框
  • click on the [ Add ] button twice to add your two columns to the index 单击[ Add ]按钮两次,将两列添加到索引中

在此输入图像描述

When you've done those two steps, you now have a unique index on the (CatID, AliasID) combination and no pair of those two values can exist more than once in your table. 当您完成这两个步骤后,您现在在(CatID, AliasID)组合上有一个唯一索引 (CatID, AliasID)并且这两个值中的任何一对都不能在表中存在多次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM