SQL Server:当表a中的单行更新时,如何更新表b?

时间:2017-10-21 18:07:46

标签: sql sql-server triggers

我已经创建了一个SQL Server触发器,当他的一个病人改变状态到#34; kill"时,它应该给医生添加一个kill。但我不知道如何获得更新的一行。从现在看来,医生也会为之前患过的每位患者获得病人++。

我该如何解决这个问题?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[PatientKilled] 
ON [dbo].[Patient]
AFTER UPDATE 
AS
BEGIN
    DECLARE

    SET NOCOUNT ON;

    UPDATE Doctor 
    SET PatientsKilled += 1 
    FROM Doctor d 
    INNER JOIN inserted p ON d.DoctorId = p.DoctorId 
    WHERE p.PatientState = 'Killed' 
END

2 个答案:

答案 0 :(得分:1)

“杀人”这个词意味着医生是杀人的,但无视这个问题,这应该做你需要的。

您应该检查以前的状态,只有在更改后才会增加计数器。我假设“Killed”是一个永久状态,所以不需要添加逻辑来减少。你应该考虑是否需要它。

WITH p AS
(
SELECT COUNT(*) AS NewKills, 
               I.DoctorId
FROM INSERTED I JOIN DELETED D
ON I.PatientId = D.PatientId
WHERE I.PatientState = 'Killed'  
    AND (D.PatientState <> 'Killed' OR D.PatientState IS NULL)
GROUP BY I.DoctorId
)
UPDATE d
SET PatientsKilled += NewKills
FROM Doctor d 
    INNER JOIN p ON d.DoctorId = p.DoctorId 

答案 1 :(得分:0)

USE [AD17_Hospital]
GO
/****** Object:  Trigger [dbo].[PatientKilled]    Script Date: 2017-10-21 19:51:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[PatientKilled] ON [dbo].[Patient]
AFTER UPDATE 
AS
BEGIN

SET NOCOUNT ON;
UPDATE Doctor 
SET PatientsKilled (SELECT COUNT(*) FROM Patients WHERE DoctorID = INSERTED.DoctorID AND PatientState = 'Killed')
FROM Doctor d 

END