'SQL Trigger based on a condition in another table with several rows (UPDATE)
I am trying to create a trigger on one table that is conditional on what could be several rows in another table.
Table 1 = sysid, decision
Table 2 = sysid, user, status
Table 1 = 1, Pending
Table 2 = 1, Lisa, Approved
Table 2 = 1, Maggie, Approved
Table 2, = 1, Nancy, Pending
I Need Table 1 to change to Approved once Nancy has approved her record.
I need to update decision in table 1 if all the records have a status of approved in table 2
I am getting an update error. Can someone help please. I think it is the multiple records in table 2 that is causing the issue. If the trigger I'm posting is too confusing, just use the description. I am on 2012. Thank you.
CREATE TRIGGER [TR_] ON [Table 2]
AFTER UPDATE
AS
if (UPDATE (T2.status))
BEGIN
SET NOCOUNT ON;
update table 1
Set T1.decision = 'Approved'
from
(
select DISTINCT sysid
from(
Select T1.sysId T2.status
,LAG(T2.status) OVER(PARTITION BY T1.sysid Order by T1.sysid) as
previousrecord
from table 1
left join table 2 on T2.sysid=T1.sysId
Where decision <> 'Approved'
)x
where status = 'Approved' and previousrecord = 'Approved' OR (status =
'Approved'
and previousrecord IS
NULL)
) z
where sysid = z.sysid
END;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
