现在触发器看起来像这样,部分工作
我的触发器看起来像这样
ALTER trigger [dbo].[tr_EligebilityCheck]
on [dbo].[Clients]
for INSERT,update
as
BEGIN
UPDATE Clients
SET
StatusID = 5
WHERE
ClientID IN (Select ClientID
from Clients c
join inserted --ADD THIS JOIN
on inserted.ClientID = c.ClientID
join IncomeEligibility i
on c.HshldSize = i.HshldSize
where StatusID in (1,2)
and WIC = 0
and (c.CategCode = 'SR'
and ((MonthlyYearly = 'month' and c.AnnualHshldIncome >= i.SeniorMo)
or (c.AnnualHshldIncome >= i.SeniorYr and MonthlyYearly ='year'))
and DATEDIFF(YEAR,DOB,GETDATE()) < 60)
or
(c.CategCode = 'CH'
and ((MonthlyYearly = 'month' and c.AnnualHshldIncome >= i.WomanChildMo)
or (c.AnnualHshldIncome >= i.WomanChildYr and MonthlyYearly ='year'))
and DATEDIFF(YEAR,DOB,GETDATE()) > 6))
update Clients
set StatusID = 4
where WIC =1
from Clients --ADD THIS FROM STATEMENT
join inserted --ADD THIS JOIN
on inserted.ClientID = Clients.ClientID
END
当我使用CategCode ='SR'插入客户端时,如果客户端小于60,则仅检查DOB并触发,但如果客户端较旧,则不检查此
and ((MonthlyYearly = 'month' and c.AnnualHshldIncome >= i.SeniorMo)
or (c.AnnualHshldIncome >= i.SeniorYr and MonthlyYearly ='year'))
如果我使用CategCode ='CH'插入客户端,则检查收入但未检查DOB。
答案 0 :(得分:1)
只要您对主键有正确的引用,我就不明白为什么您需要INSTEAD OF
触发器。似乎没有任何情况可以防止插入或更新,对吗?您只想确定StatusID的值。在更新之前没有理由要做。
我相信你更新了太多行的原因是你没有将触发器限制在inserted
表中的那些行。尝试在触发器中添加联接,如下所示:
ALTER trigger [dbo].[tr_EligebilityCheck]
on [dbo].[Clients]
for INSERT,update
as
BEGIN
UPDATE Clients
SET
StatusID = 5
WHERE
ClientID IN (Select ClientID
from Clients c
join inserted --ADD THIS JOIN
on inserted.ClientID = c.ClientID
join IncomeEligibility i
on c.HshldSize = i.HshldSize
where StatusID in (1,2)
and WIC = 0
and (c.CategCode = 'SR'
and ((MonthlyYearly = 'month' and c.AnnualHshldIncome >= i.SeniorMo)
or (c.AnnualHshldIncome >= i.SeniorYr and MonthlyYearly ='year'))
and DATEDIFF(YEAR,DOB,GETDATE()) < 60)
or
(c.CategCode = 'CH'
and ((MonthlyYearly = 'month' and c.AnnualHshldIncome >= i.WomanChildMo)
or (c.AnnualHshldIncome >= i.WomanChildYr and MonthlyYearly ='year'))
and DATEDIFF(YEAR,DOB,GETDATE()) > 6))
update Clients
set StatusID = 4
where WIC =1
from Clients --ADD THIS FROM STATEMENT
join inserted --ADD THIS JOIN
on inserted.ClientID = Clients.ClientID
END
如果您确实想要使用INSTEAD OF
触发器,请注意以下几点:INSTEAD OF
不与BEFORE UPDATE
相同。 BEFORE UPDATE
更改inserted
表,然后继续更新。 INSTEAD OF
完全取消插入或更新,这意味着您需要明确地重写它。我有一个例子如下。
此外,如果您想使用INSTEAD OF
触发器,则需要单独的INSERT
和UPDATE
触发器,或者您需要将查询编写为{{ 1}}陈述。我将在下面的示例中使用MERGE
:
INSERT