Insert 2 rows that are linked in both directions in SQL

I have two tables like this:

// Person.Details Table:
PersonID int [PK] | EmployeeCreatorID int [FK] | FirstName varchar | OtherInfo...

// Employee.Details Table:
EmployeeID int [PK] | PersonID int [FK] | IsAdmin bit | OtherInfo...

Each table is associated with another:

[Employee.Details.PersonID]===>[Person.Details.PersonID] AND
[Person.Details.EmployeeCreatorID]===>[Employee.Details.EmployeeID]

through their foreign keys.

The problem is that it is not possible to create the first person / employee without removing one of the foreign key constraints, inserting the rows, and then adding the constraint (which is pretty weak).

The obvious paradox of God here is that the first “Worker" does not exist to create himself ("Personality").

Is there a way to insert data into two tables at the same time? This creator-creator script should happen only once. If I can't insert data into two tables at the same time, are there any other methods that you offer SO geniuses?

EXPLANATIONS

, ""... , "" "". (Employee Student Guardian, ). Employee, ManagerID FK; .

b0fh

--/*seeds database with first employee*/
BEGIN TRAN
GO
INSERT INTO Person.Details
    (EmployeeCreatorID, FirstName, Active)
VALUES
    (@@Identity, 'Admin', 1)
DECLARE @Identity int;
SET @Identity = @@Identity;
INSERT INTO Employee.Details 
    (PersonID, IsAdmin, Email, Password) 
VALUES
    (@Identity, 1, 'admin', 'admin')
UDPATE
    Person.Details
SET
    EmployeeCreatorID = @@Identity
WHERE
    PersonID = @Identity

IF(@@ERROR <> 0)
    ROLLBACK TRAN
ELSE
    COMMIT TRAN
+3
5

NULL . Person NULL CreatorID, .

, (Person, Employee), , , .

+3

SQL-, , , . BEGIN; COMMIT;.

+2

db. imho.

+1

, , , , . :

  • .
  • - .

, ? ? , , , , ?

, , . - EmployeeCreaterId PersonCreatorId ( ), PersonCreatorId .

0

, . , . , , , employeeeecreatorid fk . . . , personID FK employee, . Person, EmployeeCreatorId EmployeeID FK EmployeeCreatorID .
, , .

This will avoid all changes and re-create keys every time a new person is created. Good luck.

0
source

Source: https://habr.com/ru/post/1734337/


All Articles