我是触发器的新手,我似乎无法找到这个问题的答案。
我需要在表中插入计算的行并且无法访问应用程序源代码。我认为解决方法可能是在表上创建一个触发器以根据插入的值计算值,然后将它们插入表中,尽管我不确定这是如何工作的。
我有以下触发器,它适用于更新,但不适用于插入。如果我在“FOR INSERT, UPDATE”中删除“INSERT”,它将插入 account_id 字段(这是唯一的非空字段),但不会插入其余字段。如果我留下“INSERT”,它不会插入任何字段。
我怎样才能使这对插入和更新都有效?
ALTER TRIGGER [dbo].[SelfCalFieldsTrigger]
ON [dbo].[dynTable]
FOR INSERT, UPDATE
AS
BEGIN
Declare @acctID uniqueidentifier
Declare @invDiscPremPerc decimal(9,6)
Declare @investorSRP decimal(9,6)
Declare @purchWireAmt decimal(11,2)
set @acctID = (Select account_id from inserted)
set @invDiscPremPerc = (Select Coalesce(INVESTOR_DISC_PREM_DOLLAR, 0)/
Coalesce(INVESTOR_PRIN_BAL_PURCHASED, 0)*100 from inserted)
set @investorSRP = (Select Coalesce(INVESTOR_SRP_PREM_DOLLAR, 0)/
Coalesce(INVESTOR_PRIN_BAL_PURCHASED, 0)*100 from inserted)
set @purchWireAmt = (Select Coalesce(INVESTOR_PRIN_BAL_PURCHASED, 0)-
Coalesce(INVESTOR_ADMIN_FEE, 0)-
Coalesce(INVESTOR_WIRE_FEE, 0)- Coalesce(INVESTOR_FLOOD_FEE, 0)-
Coalesce(INVESTOR_TAX_SERVICE_FEE, 0) - Coalesce(INVESTOR_OTHER_FEE, 0) from
inserted)
UPDATE [dbo].dynTable]
set INVESTOR_DISC_PREM_PERCENT = @invDiscPremPerc,
INVESTOR_SRP = @investorSRP,
PURCHASE_WIRE_AMOUNT = @purchWireAmt
Where [dbo].[dynTable].Account_ID = @acctID
END