I had written about a FK in a CREATE TABLE statement recently, but the second half of this was that after the original question, the person asked if this would also work for a self-referencing FK. It does, and I wrote this to show that.
Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.
Creating the FK
The last post showed how to create the FK, but this works within a table as well. Let’s say I want to have an Employee table that links back one employee to another, who is their manager. That type of structure looks like this:
CREATE TABLE [dbo].[Employee]( [EmpID] [INT] NOT NULL, [EmpName] [VARCHAR](20) NULL, [MgrID] [INT] NULL, CONSTRAINT [EmployeePK] PRIMARY KEY CLUSTERED ( [EmpID] ASC ) ) ON [PRIMARY] GO
I can add a link that makes MgrID a FK reference by altering the code like this:
CREATE TABLE [dbo].[Employee]( [EmpID] [INT] NOT NULL, [EmpName] [VARCHAR](20) NULL, [MgrID] [INT] NULL, CONSTRAINT [EmployeePK] PRIMARY KEY CLUSTERED ( [EmpID] ASC ), CONSTRAINT FK_MgrID_EmpID FOREIGN KEY (MgrID) REFERENCES dbo.Employee (EmpID) ) GO
Easy.
SQL New Blogger
This is a post that took me less than 10 minutes to write. I changed the code from the previous post and wrote this right after the other one. The search and replace was the longest code part, and then the writing was quick, 5 minutes.
This is a core skill for a DBA or developer. Write your own post to show how and why to build a self referencing FK for some scenario that you work with in your job, or in a project.