2016-04-09 18 views
-2

前の投稿(linked here)と同じように、私はテーブルを設計していましたが、の特定の値のみを挿入するようにを試しています。BrothersNameの列には、制約。テーブルに外部キーを追加する

TABLE Family 
(
    BrothersName varchar(30) 
); 

私の質問は、私が外部キーで代わりにこれを実行しようとしていることです。それを行う唯一の方法は、新しいテーブルを作成し、そのテーブルに主キーを追加することですか?

これ以外の方法は何ですか?

答えて

1

ですから、今、あなたはintとしてFamilyテーブルに外部キーIDを保持する必要があります

create table MasterBrotherNames (ID int IDENTITY(1,1) PRIMARY KEY, Name nvarchar(30)) ; 
insert into MasterBrotherNames(Name) values (N'Alex'),(N'Tom'); 

以下のような弟名に設定可能なすべてのマスタデータを保持するために、プライマリキーテーブルを持っている必要があり、使用してカラムBrothersNameIDで言います

insert into Family values (1)-- for Alex 
insert into Family values (2)-- for Tom 
insert into Family values (3)-- this gives error 
--The INSERT statement conflicted with the FOREIGN KEY constraint "fk_family_brothername". 
以下のtryクエリをテストするには

create table Family(BrothersNameID int NOT NULL); 
alter table Family add constraint fk_family_brothername foreign key (BrothersNameID) references MasterBrotherNames (ID); 

FK関係を作成するには、次のクエリOPの次のリクエスト

に基づき

値として名前だけが挿入され、受け入れ可能なMasterBrothersNameのいずれかのIDを持つことなく、これを実装する方法、ここで変更クエリ

だがあります
create table MasterBrotherNames (Name nvarchar(30) PRIMARY KEY) ; 
insert into MasterBrotherNames(Name) values (N'Alex'),(N'Tom'); 

create table Family(BrothersName nvarchar(30) NOT NULL); 
alter table Family add constraint fk_family_brothername foreign key (BrothersName) references MasterBrotherNames (Name); 

insert into Family values (N'Alex')-- for Alex 
insert into Family values (N'Tom')-- for Tom 
insert into Family values (N'A')-- this gives error 
--The INSERT statement conflicted with the FOREIGN KEY constraint "fk_family_brothername". 
+0

あなたのお返事ありがとうございます。これは私が理解するのが少し難しいですが、 'MasterBrothersName'にIDを入れずに実装する方法はありますか?名前だけを挿入して値として受け入れることができますか?例えば、「ファミリー(BrothersName)値( 'Alex')の値に挿入する」のようなものです。 –

+0

@Tomb_Raider_Legend更新しました。 – DhruvJoshi

関連する問題