简体   繁体   English

如何在SQL Server中使用触发器更新外键引用表?

[英]How to update foreign key referenced table using trigger, in SQL Server?

Say I have these tables: 说我有这些表:

CREATE TABLE person 
(
    person_id INT NOT NULL PRIMARY KEY,
    name VARCHAR NOT NULL,
    phone INT,
);

CREATE TABLE volunteers 
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

Could I create a trigger on volunteers that could insert into person table when I insert a new record in volunteers table. 我可以在volunteers person上创建一个触发器,当我在volunteers person表中插入新记录时将其插入person表。

Like this: 像这样:

INSERT INTO volunteers (person_id, name, skill) 
VALUES (12345, 'abc xyz', 'cooking');

If not using trigger, is there any alternatives? 如果不使用触发器,还有其他选择吗?

I'm not going to write the code for you, but you can do the following: 我不会为您编写代码,但是您可以执行以下操作:

  • Create a view with all the columns you want, joining the tables. 用所需的所有列创建一个视图,将这些表联接在一起。
  • Write an instead of trigger to update the view 写一个instead of触发器来更新视图

The use of such triggers on views is defined in the documentation . 文档中定义了在视图上使用此类触发器的方法。

The view would look like: 该视图如下所示:

create view v_volunteers as 
    select v.person_id, p.name, v.skill
    from volunteers v join
         people p
         on p.person_id = v.person_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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