在第一个 table 中插入主键后,如何使用触发器将主键插入另一个 table 中?

How to insert a primary key into another table with a trigger after inserting it in the first table?

我的数据库包含两个 table;每个 table 在列 ID 上都有主键。

第一个 table, tbl_Person 也有一个外键引用第二个 table, tbl_Address:

tbl_Person           tbl_Address
+----+------+        +----+---------+
| ID | Name |        | ID | Address |
+----+------+        +----+---------+
| 1  | Jim  |  --->  | 1  |  .....  |
| 2  | Tim  |        | 2  |  .....  |
| 3  | Kim  |        | 3  |  .....  |
+----+------+        +----+---------+

我现在想知道如何创建触发器,将新插入的人的 ID 插入第二个 table、tbl_Address 并设置 [的所有其他属性=16=] 到 NULL。

我当前的触发器如下所示:

CREATE TRIGGER tg_Person 
ON tbl_Person
BEFORE INSERT
AS 
BEGIN
   DECLARE @ID INT
 
   SELECT @ID = SCOPE_IDENTITY()
   FROM tbl_Person

   INSERT INTO tbl_Address (ID)
   VALUES (@ID)
END

您需要引用 inserted 伪对象:

CREATE TRIGGER trg_CreatePersonAddress ON dbo.Tbl_Person
AFTER INSERT AS
BEGIN

    INSERT INTO dbo.tbl_Address(ID) --Should this not be PersonID?
    SELECT ID
    FROM inserted;

END;
GO