更新TRIGGER与条件回复后

时间:2016-04-14 22:22:08

标签: sql-server database-trigger

我在tblVisitLog上写了一个After Update Trigger,当特定字段TimeOUT更新时,tblClinicalDoc中的新记录被INSERTED。目标表中可能已存在具有标识ID(Encounter_code)的记录,因此我为UPDATE或INSERT语句添加了IF EXIST和IF NOT EXISTS。

我确信必须有一种比我更优雅和有效的方式来编写这个触发器。这就是我所拥有的:

    USE [test_db1]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[CreateRowInClinicalDoc]
ON [dbo].[tblVisitLog]
AFTER UPDATE

AS 
BEGIN
SET NOCOUNT ON;

IF UPDATE(TimeOUT)

IF EXISTS (SELECT c.Encounter_code FROM tblClinicalDoc c
INNER JOIN INSERTED i ON c.Encounter_code = i.Encounter_code
WHERE I.TimeOut IS NOT NULL)


UPDATE tblClinicalDoc
SET EditDate = GetDate()
FROM INSERTED i
INNER JOIN tblClinicalDoc c ON c.Encounter_code = i.Encounter_code
END

BEGIN
SET NOCOUNT ON;

IF NOT EXISTS (SELECT c.Encounter_code FROM tblClinicalDoc c
INNER JOIN INSERTED i ON c.Encounter_code = i.Encounter_code
WHERE I.TimeOut IS NOT NULL)

INSERT INTO tblClinicalDoc 
SELECT DISTINCT v.CaseNumber AS CaseNumber, v.Episode AS Episode, v.Encounter_code AS Encounter_code, v.Provider AS Provider, 
(r.Discipline + '_'+ r.ReportType) AS Note_Type, (r.Discipline + '_' +r.ReportType + ' - ' + v.Case_Name + ' ' + convert(nvarchar(10), 
v.TimeIN, 112)) AS Note_Synopsis,
(UPPER(w.ClientCode) + '_' + v.Discipline + '_' + v.VisitType + '_' + RIGHT('0000000' + CONVERT(VARCHAR,v.Encounter_code), 7)+ '_' + convert(nvarchar(10), v.TimeIN, 112) + '.pdf') AS Document_Name,
GetDate() AS EditDate, v.Provider AS EditBy, '' AS InterfaceDate, '' AS InterfaceAgent, '-2' AS Sent, 0 AS Ack, '' AS Document_ID, '' AS Confired
FROM inserted v
INNER JOIN [WebLoginSelector].[dbo].LookupDatabaseCode w ON DB_NAME() = w.ClientDatabaseCode
INNER JOIN LookupReportTypes r ON v.Discipline = r.Discipline AND v.VisitType = r.VT
WHERE v.TimeOUT IS NOT NULL
END
GO

提前感谢所有回复,

JackW9653

0 个答案:

没有答案