我有一个如下表所示,初始插入将向“Cur_cost_unit”字段添加一个值,其中“Pre_cost_unit”默认值为0.当我将“Cur_cost_unit”更新为新值时,“Pre_cost_unit”需要用旧的“Cur_cost_unit”值更新,基本上成为“Cur_cost_unit”的历史值。我需要知道我的触发器是否会同时更新两个字段,“Cur_cost_unit”获取新值,Pre_cost_unit“获取”Cur_cost_unit“的历史值?
我的表:
create table [Prod_Cost]
(
[Ent_id] int not null IDENTITY,
[Prod_name] nvarchar(50) not null,
[Prod_code] nvarchar(50) not null UNIQUE,
[Prod_id] int not null CONSTRAINT [PK_PRODUCT_ID] PRIMARY KEY,
[Cur_cost_unit] money not null DEFAULT(0),
[Pre_cost_unit] money not null DEFAULT(0),
[Dte_Captured] datetime not null,
[Captured_by] char(50) not null
);
我的触发器:
CREATE TRIGGER Update_Cur_CostUNIT_2PreV
ON [Prod_Cost]
AFTER UPDATE
AS
DECLARE @Cur_cost_unit MONEY;
DECLARE @Prod_code NVARCHAR(50);
SELECT @Cur_cost_unit=i.[Cur_cost_unit] FROM inserted i;
SELECT @Prod_code = i.[Prod_code] from inserted i;
BEGIN
SET NOCOUNT ON;
BEGIN
UPDATE [Prod_Cost]
SET [Pre_cost_unit] = (SELECT [Cur_cost_unit] FROM [Prod_Cost] where [Prod_code] = @Prod_code),
[Cur_cost_unit] = @Cur_cost_unit
END
END
GO
非常感谢提前
答案 0 :(得分:0)
您可能正在寻找与此相似的更新
UPDATE pc
SET pc.Pre_cost_unit = d.Cur_cost_unit
FROM [Prod_Cost] pc
JOIN INSERTED i ON i.Ent_id = pc.Ent_id -- new values
JOIN DELETED d ON d.Ent_id = i.Ent_id -- previous values
答案 1 :(得分:0)
我想你可能想要一些(未经测试的)
CREATE TRIGGER Update_Cur_CostUNIT_2PreV
ON [Prod_Cost]
AFTER UPDATE
AS
UPDATE Prod_Cost
SET Prod_Cost.Pre_cost_unit = deleted.Cur_cost_unit
FROM Prod_Cost
JOIN deleted
ON Prod_Cost.Ent_id = deleted.Ent_id