我有一个包含2个主要功能的触发器
第一个函数运行良好,升级AccountType
,另一个不稳定,在另一个表中为此操作插入history
- > AccountTypeMonior ,
Create TRIGGER [dbo].[CustomerAccountUpgrade]
ON [dbo].[Customer]
AFTER UPDATE
AS
Declare
@None nvarchar(10) = 'None',
@Standard nvarchar(10) = 'Standard',
@Basic nvarchar(10) ='Basic',
@Classic nvarchar(10) ='Classic',
@Golden nvarchar(10) ='Golden',
@Platinum nvarchar(10) = 'Platinum'
-- Regular Customers
BEGIN
BEGIN
UPDATE dbo.Customer
SET AccountTypeID =
Case
When (i.TotalSales < 0)
Then 0
When (i.TotalSales = 0)
Then 10
When (i.TotalSales BETWEEN 1 AND 5000)
Then 8
When (i.TotalSales BETWEEN 5000.01 AND 10000)
Then 3
When (i.TotalSales BETWEEN 10000.01 AND 20000)
Then 4
When (i.TotalSales > 20000)
Then 5
End
FROM Inserted i JOIN Deleted d ON i.ID = d.ID -- use the primary key here
WHERE d.AccountNumber = i.AccountNumber
AND i.TotalSales != d.TotalSales -- TotalSales was updated
AND dbo.Customer.ID = i.ID -- use the PK here
AND i.CustomText1 != '1' AND i.CustomText2 ! = 'S' -- Not Assinged or Starhouse
-- After Update Insert History to Account Type Monitor Table
INSERT INTO AccountTypeMonitor (ReferenceID,ReferenceType,OldSales,NewSales ,[Status] ,FromType,ToType,DateCreated )
(SELECT
i.ID,'AccountType',d.TotalSales,i.TotalSales,
Case
When i.TotalSales > d.TotalSales Then
'Upgrade'
When i.TotalSales < d.TotalSales Then
'Downgrade'
End
,
Case
When d.AccountTypeID = 0
Then @None
When d.AccountTypeID = 3
Then @Classic
When d.AccountTypeID =4
Then @Golden
When d.AccountTypeID = 5
Then @Platinum
When d.AccountTypeID = 8
Then @Basic
End,
Case
When (i.AccountTypeID = 0)
Then @None
When (i.AccountTypeID = 8)
Then @Standard
When (i.AccountTypeID = 8)
Then @Basic
When (i.AccountTypeID = 3)
Then @Classic
When (i.AccountTypeID =4)
Then @Golden
When (i.AccountTypeID =5)
Then @Platinum
End,
GetDate()
FROM Inserted i JOIN Deleted d ON i.ID = d.ID -- use the primary key here
WHERE d.AccountNumber = i.AccountNumber
AND i.TotalSales != d.TotalSales -- TotalSales was updated
AND i.CustomText1 != '1' AND i.CustomText2 ! = 'S'
)
END
问题:
当我为客户进行交易时,它的升级很好,但我在历史表中设置了错误的数据
像这样001 New Test Regular 0 11000 Upgrade Golden Golden 2015-07-25 11:52:35.840 Account Number: 001 has Upgrade from Golden to Golden
例如:
基本到黄金
不是
Golden To Golden
答案 0 :(得分:1)
我怀疑问题在于游标中的AccountTypeID处理与您正在运行的实际更新子句。既然您还没有包含所有内容,那么您的代码中没有其他内容可以包含在可以解释它的问题中。
解决方案很简单,从光标中删除AccountTypeID的更新逻辑,因为无论如何都是错误的方法。从表中删除列,并添加计算列以替换它:
alter table Customer add AccountTypeID as
Case
When TotalSales < 0 Then 0
When TotalSales = 0 Then 10
When TotalSales <= 5000 Then 8
When TotalSales <= 10000 Then 3
When TotalSales <= 20000 Then 4
else 5
end
这样,数据始终是最新的,没有任何触发器。