2011-06-11 78 views
1

我使用列名ID的table1,並且使用列名ID的table2。表1中的Id列是主鍵,但在第二個表中不是,但是我想向table1.ID列添加一個限制,不接受其他table2.ID以外的值。這是否可能?如果是這樣,這怎麼能在SQL Server中完成?將約束添加到引用另一個表的列的列

回答

0

是的,它是... 你必須做出一對多的關係 - FOREIGN KEY約束。

你可以通過做一個ALTER語句來做到這一點。它可以做,如果沒有限制被違反

0

以下是創建一個外鍵關係的一個例子:

create table Table1 (id int primary key) 
create table Table2 (id int foreign key references Table1(id)) 

在數據庫的設計,這就是所謂的表2和表1之間的「一個一對多」的關係。 Table1中的一行可能與表2中的許多行有關。 Table1中的一行可能只與Table2中的一行有關。

0

我想一個contraint添加到table1.ID 列不接受值之外 腋臭table2.ID

表一個

標識列是主鍵

這是隻有在Table2中的ID列被定義爲唯一鍵或主鍵時纔可以使用外鍵約束。

這將工作:

create table Table2 (id int unique) 
create table Table1 (id int primary key foreign key references Table2(id)) 

這也將工作:

create table Table2 (id int primary key) 
create table Table1 (id int primary key foreign key references Table2(id)) 

這不起作用:

create table Table2 (id int) 
create table Table1 (id int primary key foreign key references Table2(id)) 
0

您參考第一表列 「ID」 爲第二張表的外鍵。

相關問題