views:

12840

answers:

4

I have never "hand coded" creation code for SQL Server and foreign key deceleration is seemingly different from SQL Server and Postgres...here is my sql so far:

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
);

when I run the query I get this error:

Msg 8139, Level 16, State 0, Line 9 Number of referencing columns in foreign key differs from number of referenced columns, table 'question_bank'.

Can you spot the error? thanks.

+7  A: 
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,
    foreign key ( question_exam_id ) references exams (exam_id)
);
John Boker
It can also be helpful to name the foreign key constraint. This helps with troubleshooting fk violations. For example:"foreign key fk_questionbank_exams ( question_exam_id ) references exams (exam_id)"
John Vasileff
+4  A: 

You can also name your foreign key constraint by using

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

Sara Chipps
+6  A: 

And if you just want to create the constraint on its own, you can use ALTER TABLE

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

I would recommend the syntax mentioned by Sara Chipps for inline creation, just because I would rather name my own constraints.

AlexCuse
A: 

Like you, I don't usually create foreign keys by hand, but if for some reason I need the script to do so I usually create it using ms sql server management studio and before saving then changes, I select Table Designer | Generate Change Script

vitorsilva