0

I am very much use to work with ORM (e.g. EF, L2S). So, finding difficulty writing queries.

I've created an Employee table also few masters like Department, Area.

Schema is something like:

  • Employee (Id, Name, DeptId, AreaId, ManagerId)
  • Area (Id, Name)
  • Department (Id, Name)

Now, I want to add constraint in ONE GO.

Something like,

ALTER TABLE EMPLOYEE 
ADD CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] FOREIGN KEY (DEPTID) REFERENCES DEPARTMENT(ID)
ADD CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] FOREIGN KEY (AREAID) REFERENCES AREA(ID)
ADD CONSTRAINT [FK_EMPLOYEE_EMPLOYEE] FOREIGN KEY (MANAGERID) REFERENCES EMPLOYEE(ID) --Self Reference

but, I know this is syntax error.

So, please correct my script to enable me to do this. I don't want add constraint one by one.

Thanks in advance.

2
  • 1
    The spec shows that you need to add a comma after each ADD CONSTRAINT line Commented Mar 20, 2014 at 9:29
  • Yes.it is like that. I am not aware about syntax very much. Is it possible? Commented Mar 20, 2014 at 9:31

3 Answers 3

2

Try this:

ALTER TABLE EMPLOYEE ADD 
    CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] 
               FOREIGN KEY (DEPTID) REFERENCES DEPARTMENT(ID),
    CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] 
               FOREIGN KEY (AREAID) REFERENCES AREA(ID),
    CONSTRAINT [FK_EMPLOYEE_EMPLOYEE] 
               FOREIGN KEY (MANAGERID) REFERENCES EMPLOYEE(ID)
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, That i know but, Is it possible in one ALTER TABLE statement?
The question is how NOT to do that. Besides, GO is not a valid T-SQL command
@DipalMehta try the above
1

You just need to separate each constraint with a comma, eg:

ALTER TABLE EMPLOYEE 
  ADD CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] FOREIGN KEY (DEPTID) REFERENCES DEPARTMENT(ID),
      CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] FOREIGN KEY (AREAID) REFERENCES AREA(ID),
      CONSTRAINT [FK_EMPLOYEE_EMPLOYEE] FOREIGN KEY (MANAGERID) REFERENCES EMPLOYEE(ID) 

You can find the syntax of the ALTER TABLE statement in the MSDN documentation and in Books Online

Comments

0

works with comma. Your query was perfect.

ALTER TABLE EMPLOYEE 
ADD CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] FOREIGN KEY (DEPTID) REFERENCES DEPARTMENT(ID),
ADD CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] FOREIGN KEY (AREAID) REFERENCES AREA(ID),
ADD CONSTRAINT [FK_EMPLOYEE_EMPLOYEE] FOREIGN KEY (MANAGERID) REFERENCES EMPLOYEE(ID) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.