SQL在table1上发生新插入时在table2中创建行

时间:2017-05-20 13:49:59

标签: sql postgresql database-trigger

我有一张桌子appointments(id,time,patientID,doctorID,daignosis) 和PostgreSQL中的表medical_folder(id,patientID,cure,drug_id)

我想制作一个触发器和一个函数,当有一个诊断的新约会时,它会在medical_folder中插入一个新行,其中包含一个新的id,patientID(来自约会),cure = XXX和drug_id = YYY

1 个答案:

答案 0 :(得分:0)

以触发器(MSSQL)开始的示例

CREATE TABLE appointments 
(id int, 
patientId int, 
doctorId int, 
diagnostics varchar(200))
GO

CREATE TABLE medical_folder
(id int, 
patientId int, 
cure int, 
drug_id int)
GO

CREATE TRIGGER InsteadTrigger on appointments
INSTEAD OF INSERT
AS
BEGIN
  INSERT INTO medical_folder
       SELECT ISNULL((SELECT MAX(id) from medical_folder),0)+1, patientId, 0, 0
       FROM inserted
END;
GO

INSERT INTO appointments
VALUES 
(1,1,1,'YES')

GO 

SELECT * FROM medical_folder