简体   繁体   中英

When inserting a new row in table A, another row also gets inserted in table B

So I am working with these two tables, Dependency and DependencyList .

在此处输入图片说明 在此处输入图片说明

I am trying to write an SQL query that, when a new row gets created in table Dependencies , another one also gets created in DependencyList , having the DependencyId filled with the Id of the newly created Dependency.

The Id column of both tables is auto-incremented.

Would that be possible, in any way?

You would typically do this with a FOR INSERT trigger. You can access the previously generated id using the inserted pseudo-table.

CREATE TRIGGER myTrigger ON Dependencies FOR INSERT
AS INSERT INTO DependencyList (DependencyId) SELECT Id FROM inserted;

Demo on DB Fiddlde

You can also do this with two insert statements, using SCOPE_IDENTITY() to retrieve the last insert id :

INSERT INTO Dependencies(isResolved, AssignedToTaskId) VALUES(0, 0);
INSERT INTO DependencyList (DependencyId) SELECT SCOPE_IDENTITY();

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM