[sql] SQL Server에서 외래 키를 작성하는 방법

SQL Server에 대한 “손으로 코딩 된”개체 생성 코드는 없었으며 외래 키 제거는 SQL Server와 Postgres에서 다르게 보입니다. 지금까지 내 SQL은 다음과 같습니다.

drop table exams;
drop table question_bank;
drop table anwser_bank;

create table exams
(
    exam_id uniqueidentifier primary key,
    exam_name varchar(50),
);
create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint question_exam_id foreign key references exams(exam_id)
);
create table anwser_bank
(
    anwser_id           uniqueidentifier primary key,
    anwser_question_id  uniqueidentifier,
    anwser_text         varchar(1024),
    anwser_is_correct   bit
);

쿼리를 실행할 때이 오류가 발생합니다.

메시지 8139, 수준 16, 상태 0, 줄 9 외래 키의 참조 열 수는 ‘question_bank’테이블의 참조 열 수와 다릅니다.

당신은 오류를 발견 할 수 있습니까?



답변

create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)
);


답변

구속 조건 만 작성하려는 경우 ALTER TABLE을 사용할 수 있습니다.

alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn)

Sara Chipps가 인라인 생성을 위해 언급 한 구문을 권장하지 않습니다. 단지 내 제약 조건의 이름을 지정하기 때문입니다.


답변

다음을 사용하여 외래 키 제약 조건의 이름을 지정할 수도 있습니다.

CONSTRAINT your_name_here FOREIGN KEY (question_exam_id) REFERENCES EXAMS (exam_id)


답변

AlexCuse의 답변이 마음에 들지만 외래 키 제약 조건을 추가 할 때마다주의해야 할 점은 참조 된 테이블 행의 참조 된 열에 대한 업데이트를 처리하는 방법, 특히 참조 된 행을 삭제하는 방법입니다 처리 할 테이블.

다음과 같이 구속 조건이 작성되는 경우 :

alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn )
references MyOtherTable(PKColumn)

.. 그때 참조하는 테이블의 해당 행이있는 경우 참조 된 테이블에서 업데이트 또는 삭제가 오류와 함께 날려 버리겠다.

그것은 당신이 원하는 행동 일지 모르지만, 내 경험으로는 훨씬 일반적이지 않습니다.

대신 다음과 같이 작성하십시오.

alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn )
references MyOtherTable(PKColumn)
on update cascade
on delete cascade

.. 그런 다음 상위 테이블에서 업데이트 및 삭제하면 참조 테이블의 해당 행이 업데이트 및 삭제됩니다.

(저는 기본값을 변경해야한다고 제안하는 것이 아닙니다. 기본은주의 측면에서 잘못되었습니다. 제약 만들고있는 사람 은 항상주의를 기울여야한다고 말하고 있습니다. .)

이것은 다음과 같이 테이블을 만들 때 수행 할 수 있습니다.

create table ProductCategories (
  Id           int identity primary key,
  ProductId    int references Products(Id)
               on update cascade on delete cascade
  CategoryId   int references Categories(Id)
               on update cascade on delete cascade
)


답변

create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null constraint fk_exam_id foreign key references exams(exam_id),
    question_text varchar(1024) not null,
    question_point_value decimal
);

-그것도 작동합니다. 아마도 좀 더 직관적 인 구조일까요?


답변

테이블에서 외래 키를 만들려면

ALTER TABLE [SCHEMA].[TABLENAME] ADD FOREIGN KEY (COLUMNNAME) REFERENCES [TABLENAME](COLUMNNAME)
EXAMPLE
ALTER TABLE [dbo].[UserMaster] ADD FOREIGN KEY (City_Id) REFERENCES [dbo].[CityMaster](City_Id)


답변

쿼리를 사용하여 두 개의 테이블 열을 관계로 만들려면 다음을 시도하십시오.

Alter table Foreign_Key_Table_name add constraint
Foreign_Key_Table_name_Columnname_FK
Foreign Key (Column_name) references
Another_Table_name(Another_Table_Column_name)