对于第一部分,您可以简单地添加默认约束:
alter table patient add constraint df_status default 'Registered' for status
如果这还不够,因为您的前端无法在插入中省略状态或将值设置为 DEFAULT,您可以创建一个触发器:
create trigger PatientInsertTrigger on patient
after insert
as
-- trigger should not alter @@rowcount
set nocount on
update patient
set status = 'Registered'
from Patient
-- Inserted is a pseudotable holding newly inserted rows
-- This is how we know what records to update
inner join Inserted
on Patient.ID = Inserted.ID
在诊断中添加或删除记录时,应根据诊断中匹配记录的数量更新患者状态。幸运的是,在调用触发器时,记录已经在表中,因此在这两种情况下都使用 count() 就足够了。
create trigger DiagnosisTrigger on diagnosis
after insert, delete
as
set nocount on
update patient
set status = case when d.NumberOfDiagnosis <> 0
then 'Diagnosed'
else 'Registered'
end
from Patient
inner join
(
select PatientID, count(*) NumberOfDiagnosis
from Diagnosis
-- Get all patients with added or removed diagnosis
where PatientID in (select PatientID
from Inserted
union
select PatientID
-- Pseudotable holding removed records
from Deleted)
group by PatientID
) d
on Patient.ID = d.PatientID
Status 应该是 StatusID,但您没有提及适当的 ID 号。