DROP TRIGGER hips.HospitalPatientUTrg
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================

-- Create date:   20 June 2013
-- Description:   Inserts the history record when the hospital patient is updated
-- =============================================
CREATE TRIGGER hips.HospitalPatientUTrg
ON hips.HospitalPatient
FOR UPDATE AS
BEGIN

SET NOCOUNT ON

INSERT hips.HospitalPatientHistory
       ([HospitalPatientId]
       ,[FromPatientMasterId]
       ,[ToPatientMasterId]
       ,[HospitalId]
       ,[FromMrn]
       ,[ToMrn]
       ,[DateCreated]
       ,[UserCreated]
       ,[DateModified]
       ,[UserModified])
SELECT	  inserted.PatientId
		, deleted.PatientMasterId
		, inserted.PatientMasterId
		, inserted.HospitalId
		, deleted.Mrn
		, inserted.Mrn
		, inserted.DateModified
		, inserted.UserModified
		, inserted.DateModified
		, inserted.UserModified
FROM deleted
INNER JOIN inserted ON inserted.PatientId = deleted.PatientId
WHERE	(inserted.PatientMasterId <> deleted.PatientMasterId
	OR	inserted.Mrn <> deleted.Mrn)

END
GO

DROP TRIGGER hips.PatientMasterUTrg
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================

-- Create date:   20 June 2013
-- Description:   Inserts the history record when the patient master is updated
-- =============================================
CREATE TRIGGER hips.PatientMasterUTrg
ON hips.PatientMaster
FOR UPDATE AS
BEGIN

SET NOCOUNT ON

INSERT hips.PatientMasterHistory
		   ([PatientMasterId]
           ,[FromStatePatientId]
           ,[ToStatePatientId]
           ,[DateCreated]
           ,[UserCreated]
           ,[DateModified]
           ,[UserModified])
SELECT	  inserted.PatientMasterId
		, deleted.StatePatientId
		, inserted.StatePatientId
		, inserted.DateModified
		, inserted.UserModified
		, inserted.DateModified
		, inserted.UserModified
FROM deleted
INNER JOIN inserted ON inserted.PatientMasterId = deleted.PatientMasterId
WHERE	(inserted.StatePatientId <> deleted.StatePatientId)
OR		(inserted.StatePatientId IS NULL AND deleted.StatePatientId IS NOT NULL)
OR		(inserted.StatePatientId IS NOT NULL AND deleted.StatePatientId IS NULL)

END
GO

