Error with foreign key SQL Server 2012 - sql

I have problem with adding foreign key in SQL Server 2012
create table Predracun
(
PredracunID int not null identity(1,1),
Iznos nvarchar(255),
Datum date,
Opis nvarchar(255)
)
create table Racun
(
RacunID int not null identity (1,1),
Sifra nvarchar(255),
BrojRacuna nvarchar(255)
)
create table Prijem
(
PrijemID int not null identity (1,1),
Datum date,
Opis nvarchar(255)
)
alter table Prijem
add constraint FK_PrijemPredracun
foreign key (PredracunID)
references Predracun (PredracunID)
added on this way
and I got error msg
Msg 1769, Level 16, State 1, Line 1
Foreign key 'FK_UredjajPrijem' references invalid column 'PrijemID' in referencing table 'Uredjaj'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

The column PredracunID does not exist in table prijem. Therefore it can't be used as a foreign key.

Use below scripts:
CREATE TABLE Predracun
(
PredracunID int not null identity(1,1),
Iznos nvarchar(255),
Datum date,
Opis nvarchar(255)
PRIMARY KEY CLUSTERED
(
[PredracunID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
create table Racun
(
RacunID int not null identity (1,1),
Sifra nvarchar(255),
BrojRacuna nvarchar(255)
)
create table Prijem
(
PrijemID int not null identity (1,1),
PredracunID int,
Datum date,
Opis nvarchar(255)
)
alter table Prijem
add constraint FK_PrijemPredracun
foreign key (PredracunID)
references Predracun (PredracunID)
Note: Foreign key can be created only on either primary key column or unique key column from reference table. You were missing two things in your script.
Predracun table is not having any key (Unique or Primary) column
To create foreign key in Prijem table you have to have PredracunID column in create table statement.

Related

Foreign key error in SQL Server 2014

Sorry I had to be more specific in here. So following is SQL my code. Copy and paste in SQL. Basically, I am creating 13 tables that are linked together.
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='EventType')
BEGIN
DROP TABLE EventType
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='EventLocation')
BEGIN
DROP TABLE EventLocation
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='StudentEvent')
BEGIN
DROP TABLE StudentEvent
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Event')
BEGIN
DROP TABLE Event
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='CurrentAddress')
BEGIN
DROP TABLE CurrentAddress
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='PreviousAddress')
BEGIN
DROP TABLE PreviousAddress
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='ContactType')
BEGIN
DROP TABLE ContactType
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Contact')
BEGIN
DROP TABLE Contact
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='StudentMajor')
BEGIN
DROP TABLE StudentMajor
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Major')
BEGIN
DROP TABLE Major
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Citizenship')
BEGIN
DROP TABLE Citizenship
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Country')
BEGIN
DROP TABLE Country
END
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Student')
BEGIN
DROP TABLE Student
END
GO
CREATE TABLE Student
(
StudentID int identity PRIMARY KEY,
FirstName varchar (50),
LastName varchar (30)
)
GO
CREATE TABLE Country
(
CountryID int identity PRIMARY KEY,
CountryOfBirth varchar (10),
StudentID int FOREIGN KEY REFERENCES Student(StudentID)
)
GO
CREATE TABLE Citizenship
(
CitizenshipID int identity PRIMARY KEY,
CountryOfCitizenship1 varchar (10),
CountryOfCitizenship2 varchar (10),
StudentID int FOREIGN KEY REFERENCES Student(StudentID),
CountryID int FOREIGN KEY REFERENCES Country(CountryID)
)
GO
CREATE TABLE Major
(
Majorid int identity PRIMARY KEY,
MajorName varchar(30),
GraduatedMajor varchar (30)
)
CREATE TABLE StudentMajor
(
StudentMajorid int identity,
StudentID int FOREIGN KEY REFERENCES Student(StudentID),
MajorID int FOREIGN KEY REFERENCES Major(MajorID)
)
GO
ALTER TABLE StudentMajor
ADD constraint uk_sm UNIQUE (StudentID,MajorID)
CREATE TABLE Contact
(
ContactId int identity PRIMARY KEY,
StudentID int FOREIGN KEY REFERENCES Student(StudentID),
ContactInfo varchar (8),
ContactDate datetime
)
GO
CREATE TABLE ContactType
(
ContactTypeId int identity PRIMARY KEY,
ContactID int FOREIGN KEY REFERENCES Contact(ContactID)
)
GO
CREATE TABLE PreviousAddress
(
PreviousAddressId int identity PRIMARY KEY,
Address1 varchar (50),
Address2 varchar (50),
City varchar (20),
State varchar (20),
Pincode char (10),
StudentID int FOREIGN KEY REFERENCES Student(StudentID)
)
GO
CREATE TABLE CurrentAddress
(
CurrentAddressId int identity PRIMARY KEY,
Address1 varchar (50),
Address2 varchar (50),
City varchar (20),
State varchar (20),
Pincode char (10),
StudentID int FOREIGN KEY REFERENCES Student(StudentID)
)
GO
CREATE TABLE EventType
(
EventTypeID int identity PRIMARY KEY
)
CREATE TABLE Event
(
EventId int identity PRIMARY KEY,
EventDate datetime,
EventTitle varchar (50),
EventTime datetime,
EventTypeID int
)
GO
ALTER TABLE Event
ADD constraint fk_Event
FOREIGN KEY (EventTypeID) REFERENCES EventType(EventTypeID)
CREATE TABLE StudentEvent
(
StudentEventId int identity PRIMARY KEY,
StudentID int FOREIGN KEY REFERENCES Student(StudentID),
EventID int FOREIGN KEY REFERENCES Event(EventID),
Comment varchar(2000)
)
GO
CREATE TABLE EventLocation
(
EventLocationId int identity PRIMARY KEY,
EventCountry varchar (50),
EventState varchar (50),
EventAddress1 varchar (100),
EventAddress2 varchar (100),
EventCity varchar (50),
EventPincode char (10),
EventID int FOREIGN KEY REFERENCES Event(EventID)
)
GO
Now the problem with the above code is that it will execute perfectly first time, but when I execute second time it throws me following error.
Could not drop object 'EventType' because it is referenced by a FOREIGN KEY constraint.
Msg 2714, Level 16, State 6, Line 132
There is already an object named 'EventType' in the database.
Msg 4902, Level 16, State 1, Line 143
Cannot find the object "Event" because it does not exist or you do not have permissions.
Msg 1767, Level 16, State 0, Line 153
Foreign key 'FK__EventLoca__Event__6265874F' references invalid table 'Event'.
Msg 1750, Level 16, State 0, Line 153
Could not create constraint or index. See previous errors.
Is there a better way to code the foreign key or am I doing something wrong.
Thanks in advance for help!
You should create the table first:
CREATE TABLE Event
(
EventId int identity PRIMARY KEY,
EventDate datetime,
EventTitle varchar (50),
EventTime datetime,
EventTypeID int
)
GO
CREATE TABLE EventType
(
EventTypeID int identity PRIMARY KEY
);
ALTER TABLE Event
ADD constraint fk_Event
FOREIGN KEY (EventTypeID) REFERENCES EventType(EventTypeID);
Or you can create your tables as:
CREATE TABLE EventType
(
EventTypeID int identity PRIMARY KEY
);
CREATE TABLE Event
(
EventId int identity PRIMARY KEY,
EventDate datetime,
EventTitle varchar (50),
EventTime datetime,
EventTypeID int,
constraint fk_Event FOREIGN KEY (EventTypeID) REFERENCES EventType(EventTypeID)
);
Update:
Could not drop object 'EventType' because it is referenced by a FOREIGN KEY constraint. Msg 2714, Level 16, State 6, Line 132 There is already an object named 'EventType' in the database. Msg 4902, Level 16, State 1, Line 143 Cannot find the object "Event" because it does not exist or you do not have permissions. Msg 1767, Level 16, State 0, Line 153 Foreign key 'FK__EventLoca__Event__6265874F' references invalid table 'Event'. Msg 1750, Level 16, State 0, Line 153 Could not create constraint or index. See previous errors.
This error msg is clear, you can't drop a table referenced in another table, so you have to drop the Event table first, then you can drop the EventsType table.
Try creating the table EventType before using it as a reference in the table Event.

Relations in ER diagram

I am trying to create a database for a software development company (as a free time project)
I've been struggling with this for quite a while now, it's time to ask you guys for help.
I have 3 entities, PROGRAMMER, PROGRAM and PLATFORM. A programmer can work on many platforms, a program can be worked on many platforms and a programmer can work on many programs. BUT for a specific program the programmer can only work with one platform. So I created another table called WORKS witch has the following attributes: Programmer_ID, Program_ID and Platform_ID. The first two are Primary Keys so that it meets the specifications above.
Now, is where the problem starts: Programmers can supervise a program (it's not mandatory). The supervising team meets and the database has to store a team_ID for every program and a DATE for the meeting, also a Meeting_ID but that's irrelevant.
So, I have to make a table that doesn't allow duplicates on the pair Programmer_ID - Program_ID so that the same person wont be on the same group a second time, also it has to have a Team_ID witch will be the same number as the Program_ID and it has to reference the Team_ID to the MEETING table so I can store it. How can I do such a thing?
Thank you for your time.
PS: Here is how my ER looks: ER Diagram
And this is the exported DLL in MS SQL 2012:
CREATE
TABLE CUSTOMER
(
Customer_ID NUMERIC (5) NOT NULL ,
Name CHAR (30) NOT NULL ,
PR_Guy CHAR (30) NOT NULL ,
Phone CHAR (20) NOT NULL
)
ON "default"
GO
ALTER TABLE CUSTOMER ADD CONSTRAINT CUSTOMER_PK PRIMARY KEY CLUSTERED (
Customer_ID)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
CREATE
TABLE KNOWS
(
Programmer_ID NUMERIC (5) NOT NULL ,
Prog_Lang_ID NUMERIC (3) NOT NULL
)
ON "default"
GO
ALTER TABLE KNOWS ADD CONSTRAINT KNOWS_PK PRIMARY KEY CLUSTERED (Programmer_ID,
Prog_Lang_ID)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
CREATE
TABLE MEETING_DATE
(
Meeting_ID NUMERIC (3) NOT NULL ,
DATE DATE ,
Program_ID NUMERIC (5) ,
Programmer_ID NUMERIC (5)
)
ON "default"
GO
ALTER TABLE MEETING_DATE ADD CONSTRAINT MEETING_DATE_PK PRIMARY KEY CLUSTERED (
Meeting_ID)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
CREATE
TABLE PLATFORM
(
Platform_ID NUMERIC (5) NOT NULL ,
Name CHAR (30) NOT NULL ,
OS CHAR (30) ,
Latest_Update DATE NOT NULL ,
Dev_Name CHAR (30) NOT NULL
)
ON "default"
GO
ALTER TABLE PLATFORM ADD CONSTRAINT PLATFORM_PK PRIMARY KEY CLUSTERED (
Platform_ID)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
CREATE
TABLE PROGRAM
(
Program_ID NUMERIC (5) NOT NULL ,
Name CHAR (30) NOT NULL ,
Deadline DATE NOT NULL ,
Customer_ID NUMERIC (5) NOT NULL
)
ON "default"
GO
ALTER TABLE PROGRAM ADD CONSTRAINT PROGRAM_PK PRIMARY KEY CLUSTERED (Program_ID
)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
CREATE
TABLE PROGRAMMER
(
Programmer_ID NUMERIC (5) NOT NULL ,
First_Name CHAR (30) NOT NULL ,
Last_Name CHAR (30) NOT NULL ,
Money_Status NUMERIC (1) NOT NULL
)
ON "default"
GO
ALTER TABLE PROGRAMMER ADD CONSTRAINT PROGRAMMER_PK PRIMARY KEY CLUSTERED (
Programmer_ID)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
CREATE
TABLE PROG_LANG
(
Prog_Lang_ID NUMERIC (3) NOT NULL ,
Name CHAR (30) NOT NULL
)
ON "default"
GO
ALTER TABLE PROG_LANG ADD CONSTRAINT PROG_LANG_PK PRIMARY KEY CLUSTERED (
Prog_Lang_ID)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
CREATE
TABLE SUPERVISE
(
Programmer_ID NUMERIC (5) NOT NULL ,
Program_ID NUMERIC (5) NOT NULL ,
Group_ID NUMERIC (5) NOT NULL
)
ON "default"
GO
ALTER TABLE SUPERVISE ADD CONSTRAINT SUPERVISE_PK PRIMARY KEY CLUSTERED (
Program_ID, Programmer_ID)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
CREATE
TABLE WORKS
(
Programmer_ID NUMERIC (5) NOT NULL ,
Program_ID NUMERIC (5) NOT NULL ,
Platform_ID NUMERIC (5) NOT NULL
)
ON "default"
GO
ALTER TABLE WORKS ADD CONSTRAINT WORKS_PK PRIMARY KEY CLUSTERED (Programmer_ID,
Program_ID)
WITH
(
ALLOW_PAGE_LOCKS = ON ,
ALLOW_ROW_LOCKS = ON
)
ON "default"
GO
ALTER TABLE KNOWS
ADD CONSTRAINT FK_ASS_2 FOREIGN KEY
(
Programmer_ID
)
REFERENCES PROGRAMMER
(
Programmer_ID
)
ON
DELETE
NO ACTION ON
UPDATE NO ACTION
GO
ALTER TABLE KNOWS
ADD CONSTRAINT FK_ASS_3 FOREIGN KEY
(
Prog_Lang_ID
)
REFERENCES PROG_LANG
(
Prog_Lang_ID
)
ON
DELETE
NO ACTION ON
UPDATE NO ACTION
GO
ALTER TABLE MEETING_DATE
ADD CONSTRAINT MEETING_DATE_SUPERVISE_FK FOREIGN KEY
(
Program_ID,
Programmer_ID
)
REFERENCES SUPERVISE
(
Program_ID ,
Programmer_ID
)
ON
DELETE
NO ACTION ON
UPDATE NO ACTION
GO
ALTER TABLE PROGRAM
ADD CONSTRAINT PROGRAM_CUSTOMER_FK FOREIGN KEY
(
Customer_ID
)
REFERENCES CUSTOMER
(
Customer_ID
)
ON
DELETE
NO ACTION ON
UPDATE NO ACTION
GO
ALTER TABLE SUPERVISE
ADD CONSTRAINT SUPERVISE_WORKS_FK FOREIGN KEY
(
Programmer_ID,
Program_ID
)
REFERENCES WORKS
(
Programmer_ID ,
Program_ID
)
ON
DELETE
NO ACTION ON
UPDATE NO ACTION
GO
ALTER TABLE WORKS
ADD CONSTRAINT WORKS_PLATFORM_FK FOREIGN KEY
(
Platform_ID
)
REFERENCES PLATFORM
(
Platform_ID
)
ON
DELETE
NO ACTION ON
UPDATE NO ACTION
GO
ALTER TABLE WORKS
ADD CONSTRAINT WORKS_PROGRAMMER_FK FOREIGN KEY
(
Programmer_ID
)
REFERENCES PROGRAMMER
(
Programmer_ID
)
ON
DELETE
NO ACTION ON
UPDATE NO ACTION
GO
ALTER TABLE WORKS
ADD CONSTRAINT WORKS_PROGRAM_FK FOREIGN KEY
(
Program_ID
)
REFERENCES PROGRAM
(
Program_ID
)
ON
DELETE
NO ACTION ON
UPDATE NO ACTION
GO
Could not put this in a comment since there is an image to be shown.
If your WORKS table has a primary key that has all 3 i.e. PROGRAMMER_ID, PROGRAM_ID and PLATFORM_ID then the MEETING table can be a child of the WORKS table and that I think may address your issue.
See below diagram

Adding Primary keys and a Relationship to tables

I have compiled the following as an example of what i have done so far and would like to know how i should continue:
CREATE TABLE tblMembers
(
Member_ID int,
Name varchar(255)
);
CREATE TABLE tblHorses
(
Horse_ID int,
Name varchar(255),
Age int(10),
Member_ID int(10)
);
So i would like to specify both Member_ID and Horse_ID as the PK and create the relationship between tblMembers and tblHorses using Member_ID
I would also like to make the ID columns auto incremental
Thank you in advance
Is this what you ware asking?
CREATE TABLE tblMembers (
Member_ID int identity(1, 1) not null primary key
Name varchar(255)
);
CREATE TABLE tblHorses (
Horse_ID int identity(1, 1) not nullprimary key
Name varchar(255),
Age int,
Member_ID int references tblMembers(member_id)
);
Storing something like "age" in a column is a really bad idea. After all, age continually changes. You should be storing something like the date of birth.
CREATE TABLE tblMembers
(
Member_ID int AUTO_INCREMENT,
Name varchar(255)
PRIMARY KEY (MEMBER_ID)
);
CREATE TABLE tblHorses
(
Horse_ID int,
Name varchar(255),
Age int(10),
FOREIGN KEY (MEMBER_ID) REFERENCES tblMembers(MEMBER_ID)
PRIMARY KEY (HORSE_ID)
);
Following W3Schools' examples.
Use this. Fiddler Demo
Refer this for creating Primary Key,Foreign Key, Identity .
CREATE TABLE tblMembers
(
Member_ID int IDENTITY(1,1) Primary Key,
Name varchar(255)
);
CREATE TABLE tblHorses
(
Horse_ID int IDENTITY(1,1) Primary Key,
Name varchar(255),
Age int,
Member_ID int Foreign key (Member_ID) REFERENCES tblMembers(Member_ID)
);
Note: MS SQL doesn't support length in Integer Type.
try this
CREATE TABLE [dbo].[tblMembers](
[Member_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NOT NULL,
CONSTRAINT [PK_tblMembers] PRIMARY KEY CLUSTERED
(
[Member_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[tblHorses](
[Horse_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NULL,
[Age] [int] NULL,
[Member_ID] [int] NOT NULL,
CONSTRAINT [PK_tblHorses] PRIMARY KEY CLUSTERED
(
[Horse_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tblHorses] WITH CHECK ADD CONSTRAINT [FK_tblHorses_tblMembers] FOREIGN KEY([Member_ID])
REFERENCES [dbo].[tblMembers] ([Member_ID])
GO
ALTER TABLE [dbo].[tblHorses] CHECK CONSTRAINT [FK_tblHorses_tblMembers]
GO
For Auto Incremental, you have to set PK column as identity(seed, value)
CREATE TABLE tblMembers (
Member_ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
Name VARCHAR(255)
);
CREATE TABLE tblHorses (
Horse_ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
Name VARCHAR(255),
Age INT,
Member_ID int REFERENCES tblMembers(Member_id)
);
Try below
CREATE TABLE tblMembers (
Member_ID int identity(1, 1) not null
Name varchar(255)
PRIMARY KEY (Member_ID )
);
CREATE TABLE tblHorses (
Horse_ID int identity(1, 1) not null
Name varchar(255),
Age int,
PRIMARY KEY (Horse_ID)
Member_ID int references tblMembers(member_id)
);

Creating a table with a compound primary key

Ok I want to create a table
TABLE log_table
email nvarchar(255)
,salesrep nvarchar(20)
,blastid int
,timestamp datetime
Now the default value for the timestamp would be the datetime of when the record is inserted and I want the primary key to be on email and blastid.
I know you can do it with clustered indexes but I am not sure on the syntax on how to make that happen. Please, any help would be greatly appreciated. I am using SQL Server Management Studio 2008
CREATE TABLE dbo.log_table
(
email nvarchar(255) NOT NULL,
salesrep nvarchar(2) NULL,
blastid int NOT NULL,
timestamp datetime NULL
)
ALTER TABLE dbo.log_table ADD CONSTRAINT
DF_log_table_timestamp DEFAULT GetDate() FOR timestamp
ALTER TABLE dbo.log_table ADD CONSTRAINT
PK_log_table PRIMARY KEY CLUSTERED
(
email,
blastid
)
GO
If you are using the create table GUI, you can use control while clicking columns to set as primary keys.
CONSTRAINT PK_LOG_TBL PRIMARY KEY CLUSTERED (email ASC, email ASC)
CREATE TABLE log_table (
email NVARCHAR(255) NOT NULL,
salesrep NVARCHAR(255),
blastid INT,
[timestamp] DATETIME,
PRIMARY KEY (email, blastid)
)
I believe the timestamp default would be accomplished with 'GETDATE()' on insert.
You need to create a composite primary key. the syntax is as follows:
CREATE TABLE log_table
(
email nvarchar(255),
salesrep nvarchar(20),
blastid int,
timestamp datetime,
PRIMARY KEY (email, blastid)
)
I would use something else rather than "timestamp" - that is a sql server data type.
create table log_table
(
email nvarchar(255) not null
,salesrep nvarchar(20)
,blastid int not null
,timestamp datetime default getdate())
ALTER TABLE dbo.log_table ADD CONSTRAINT
PK_log_table PRIMARY KEY CLUSTERED
(
email, blastid
) WITH( STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

Database design - How can I have a foreign key of the primary key in the same table?

My database has to store all the available departments in my company.
Some departments are sub-departments on another existing department. I've decided to solve this like this:
Departments
ID Description HeadOfDepartment ParentDepartment
ParentDepartment can be null, indicating it is a root department. If it has a parent I'll act accordingly, my question is how can I code this in Microsoft SQL?
CREATE TABLE Departments
(
ID integer primary key,
Description varchar(255),
HeadOfDepartment varchar(255),
ParentDepartment integer references Departments(ID)
);
Foreign keys in SQL Server are allowed to be either NULL OR a valid key in the appropriate table.
CREATE TABLE [hierarchytest](
[ID] [int] NOT NULL,
[ParentID] [int] NULL,
CONSTRAINT [PK_hierarchytest] PRIMARY KEY CLUSTERED
(
[ID] ASC
))
GO
ALTER TABLE [hierarchytest] WITH CHECK ADD CONSTRAINT [FK_hierarchytest_hierarchytest] FOREIGN KEY([ParentID])
REFERENCES [hierarchytest] ([ID])
GO
ALTER TABLE [hierarchytest] CHECK CONSTRAINT [FK_hierarchytest_hierarchytest]
If you create a foreign key, and enforce it, then you'll not be allowed to put null values in the foreign key field. If I were to implement something like this, I would enforce the foreign key constraint, and simply fill the foreign key value of a department with no parent with it's own primary key. That should be allowed.
CREATE TABLE Departments
(
Id INT PRIMARY KEY,
Description VARCHAR(255),
HeadOfDepartment VARCHAR(255),
ParentDepartment INT NOT NULL REFERENCES Departments(Id)
);
Create a foreign key on ParentDepartment that refrences the ID property of the table.
CREATE TABLE dbo.Departments
(
ID int NOT NULL IDENTITY (1, 1),
Description nvarchar(100) NOT NULL,
HeadOfDepartment nvarchar(100) NOT NULL,
ParentDepartment int NULL
) ON [PRIMARY]
ALTER TABLE dbo.Departments ADD CONSTRAINT
PK_Departments PRIMARY KEY CLUSTERED
(
ID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
ALTER TABLE dbo.Departments ADD CONSTRAINT
FK_Departments_Departments FOREIGN KEY
(
ParentDepartment
) REFERENCES dbo.Departments
(
ID
) ON UPDATE NO ACTION
ON DELETE NO ACTION