I have a Person
table that has a created_by
column that references the primary id of the table itself. So, it could be an employee that adds another employee to the database. It works fine.
But People
can also add themselves (signup). So the value in the created_by
column should be the auto-incremented value of the id
column. But that value is obviously not available until after the insert.
So I could either (a) make the reference not to check the values, (b) add a default value in the beginning or (c) make the column nullable. All options seem bad to me.
The MySQL's dialect has this:
SET FOREIGN_KEY_CHECKS = 0;
INSERT INTO EMPLOYEE VALUES('12345','67890'),('67890','12345');
SET FOREIGN_KEY_CHECKS = 1;
…but I could not find something similar for SQL Server's T-SQL.
Best Answer
It looks like you are using an Identity for your Primary Key. If you need flexibility with your primary key I would recommend using a sequence. it would look something like this.