Help me create a column, that shows the company’s budget. Let’s say we have three tables: Budget, Purchase, and Sale.
CREATE TABLE Budget ( ID int primary key identity(1,1) not null, BudgetAmount float not null ); CREATE TABLE PurchasingRawMaterials ( ID int primary key identity(1,1) not null, RawMaterials int foreign key (Raw Materials) references RawMaterials (ID) not null, Number int not null, Price float not null, Date date not null ); CREATE TABLE ProductSales ( ID int primary key identity(1,1) not null, Products int foreign key (Products) references FinishedProducts (ID) not null, Number int not null, Price float not null, Date date not null );
When we selling products, the budget increases, when buying raw materials, it decreases. That is, automatically when you add a value to these tables, the budget value immediately changes.
Advertisement
Answer
Use Inserted table inside the Trigger to find the recently inserted record and update the Price amount with the Budget Table.
CREATE TRIGGER TRG_PurchasingRawMaterials ON PurchasingRawMaterials AFTER INSERT AS BEGIN UPDATE B SET BudgetAmount=BudgetAmount-inserted.Price FROM Budget B INNER JOIN inserted On B.ID=inserted.RawMaterials END GO CREATE TRIGGER TRG_ProductSales ON ProductSales AFTER INSERT AS BEGIN UPDATE B SET BudgetAmount=BudgetAmount+inserted.Price FROM Budget B INNER JOIN inserted On B.ID=inserted.Products END