简体   繁体   English

检查同一表中对唯一列的约束引用

[英]Check constraint references to unique column in the same table

I have a table: 我有一张桌子:

ID     Name       ParentID
==     ====       ========
1       A          Null
2       B           1
3       C           2

so A is parent of B, and B is parent of C. 所以A是B的父,B是C的父。

I need to create a constraint for column(ParentID) which does not accept a number is not exist in column (ID). 我需要为列(ParentID)创建一个约束,它不接受列(ID)中不存在的数字。 How I would do that? 我该怎么做?

You need to add Foreign Key. 您需要添加外键。

ALTER TABLE table1 
  ADD CONSTRAINT fk_parent_id 
  FOREIGN KEY (parent_id) REFERENCES table1(id);

You can also create a foreign key using SSMS design as shown below. 您还可以使用SSMS设计创建外键,如下所示。 Expand table and right click on Keys - New Foreign key 展开表并右键单击Keys - New Foreign key

在此输入图像描述

Now click on the browse button of relationship and specify the colum nane of primary and foreign key table as shown below. 现在单击关系的浏览按钮并指定主键和外键表的列号,如下所示。

在此输入图像描述

This is one of the way and you might select the preferred way either using query or design for creating the foreign key relationships between tables in Sql Server. 这是其中一种方法,您可以选择使用查询或设计在Sql Server中创建表之间的外键关系的首选方法。

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

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