在 table A 中插入新行时,也会在 table B 中插入另一行
When inserting a new row in table A, another row also gets inserted in table B
所以我正在使用这两个 tables,Dependency
和 DependencyList
。
我正在尝试编写一个 SQL 查询,当在 table Dependencies
中创建新行时,也会在 DependencyList
中创建另一行,具有DependencyId
填充了新创建的 Dependency 的 Id
。
两个 table 的 Id
列自动递增。
这有可能吗?
您通常会使用 FOR INSERT
触发器来执行此操作。您可以使用 inserted
伪 table 访问先前生成的 id
。
CREATE TRIGGER myTrigger ON Dependencies FOR INSERT
AS INSERT INTO DependencyList (DependencyId) SELECT Id FROM inserted;
您也可以使用两个 insert
语句执行此操作,使用 SCOPE_IDENTITY()
检索最后插入的内容 id
:
INSERT INTO Dependencies(isResolved, AssignedToTaskId) VALUES(0, 0);
INSERT INTO DependencyList (DependencyId) SELECT SCOPE_IDENTITY();
所以我正在使用这两个 tables,Dependency
和 DependencyList
。
我正在尝试编写一个 SQL 查询,当在 table Dependencies
中创建新行时,也会在 DependencyList
中创建另一行,具有DependencyId
填充了新创建的 Dependency 的 Id
。
两个 table 的 Id
列自动递增。
这有可能吗?
您通常会使用 FOR INSERT
触发器来执行此操作。您可以使用 inserted
伪 table 访问先前生成的 id
。
CREATE TRIGGER myTrigger ON Dependencies FOR INSERT
AS INSERT INTO DependencyList (DependencyId) SELECT Id FROM inserted;
您也可以使用两个 insert
语句执行此操作,使用 SCOPE_IDENTITY()
检索最后插入的内容 id
:
INSERT INTO Dependencies(isResolved, AssignedToTaskId) VALUES(0, 0);
INSERT INTO DependencyList (DependencyId) SELECT SCOPE_IDENTITY();