如何在SQL Server中创建外键?

时间:2020-03-05 18:49:03  来源:igfitidea点击:

我从未为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
);

当我运行查询时,出现以下错误:

Msg 8139, Level 16, State 0, Line 9
  Number of referencing columns in
  foreign key differs from number of
  referenced columns, table
  '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)
);

回答

我们还可以使用以下方法来命名外键约束:

CONSTRAINT your_name_here 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提到的用于内联创建的语法,只是因为我宁愿命名自己的约束。

回答

像我们一样,我通常不会手动创建外键,但是如果出于某些原因需要脚本,那么我通常使用ms sql服务器管理工​​作室创建它,并且在保存然后进行更改之前,请选择"表设计器"。生成变更脚本