当我在一个表中输入新记录时,我需要将第一个表中的某些信息自动添加到第二个表中。我没有尝试使用触发器来做到这一点。
我的主表如下:
CREATE TABLE demographics (
person_local_id BIGSERIAL UNIQUE PRIMARY KEY,
first_name VARCHAR(50)...[other lines]
);
我这样设置子表:
CREATE TABLE pedigree (
pedigree_id BIGSERIAL PRIMARY KEY NOT NULL,
person_local_id BIGSERIAL NOT NULL,
person_sex VARCHAR(10),
father VARCHAR(10) DEFAULT 0,
mother VARCHAR(10) DEFAULT 0,
FOREIGN KEY (person_local_id) REFERENCES demographics (person_local_id)
ON DELETE CASCADE ON UPDATE CASCADE
);
我的方法是在人口统计主表上创建一个触发器,以便每当向其中添加一条记录时,就会将对应的记录添加到仅由person_local_id组成的血统表中。我在血统表上添加了一个外键,该外键引用了人口统计资料中的该列,我需要将其复制到该列的血统表中。
然后我创建了一个触发器,但是它不起作用。我尝试过使用“ EXECUTE”这个词。
CREATE TRIGGER into_pedigree AFTER INSERT OR UPDATE ON demographics
FOR EACH ROW EXECUTE INSERT INTO pedigree (person_local_id) SELECT (NEW.person_local_id) FROM NEW;
我不断收到语法错误,但我无法识别该错误:
ERROR: syntax error at or near "INSERT"
LINE 2: FOR EACH ROW EXECUTE INSERT INTO pedigree (person_local_id) ...
^
我也尝试过添加名称:
CREATE TRIGGER into_pedigree ON identify_relatives_database.demographics
AFTER INSERT
AS
BEGIN
INSERT INTO pedigree (person_local_id) VALUES (INSERTED.person_local_id)
END;
但是我收到错误消息:
ERROR: syntax error at or near "ON"
LINE 1: CREATE TRIGGER into_pedigree ON demographics
^
感谢您的帮助。
答案 0 :(得分:0)
您应该尝试以下方法:
postHandler
答案 1 :(得分:0)
您可以尝试这个。
CREATE TRIGGER [dbo].[Customer_INSERT]
ON [dbo].[demographics]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @CustomerId INT
SELECT @CustomerId = INSERTED.person_local_id FROM INSERTED
IF EXISTS ( SELECT * FROM PEDIGREE WHERE person_local_id = @CustomerId)
BEGIN
--- here col is the required column name need to be modified,
--- since you are inserting person_local_id from base table which is auto generated and not suppose to be change in any condition
UPDATE PEDIGREE SET COL = INSERTED.COL WHERE person_local_id = @CustomerId
END
ELSE
BEGIN
INSERT INTO pedigree (person_local_id)
VALUES(@CustomerId)
END
END
尽管我找不到与您的更新部分有关的任何内容。由于您要从基表中将主键作为子表中的外键插入,因此为了规范化,它在任何情况下都不会更改。因此,我认为您不需要在触发器中更新部分,因此所需的trigger
将是:
CREATE TRIGGER [dbo].[Customer_INSERT]
ON [dbo].[demographics]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO pedigree (person_local_id)
SELECT INSERTED.person_local_id FROM INSERTED
END