Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

sql - How do I write a trigger for such conditions? (3 tables)

I have 3 tables. When you add data to the Production table, the quantity of ingredients that are needed for this product is subtracted from the RawMaterialsWarehouse table. The Ingredients table shows the ID of the product for which it is consumed.

And the raw materials should be subtracted from the quantity specified in the Ingredients table multiplied by the production quantity

CREATE TABLE RawMaterialsWarehouse (
ID int primary key identity(1,1) not null,
Name varchar(30) not null unique,
amountperunit float not null,
quantity float not null
);

CREATE TABLE Production (
ID int primary key identity(1,1) not null,
ProductsID int foreign key (Products ID) references FinishedProductsWarehouse (ID) not null,
Quantity float not null,
Date date not null
);

CREATE TABLE Ingredients (
ID int primary key identity(1,1) not null,
ProductsID int foreign key (ProductsID) references FinishedProductsWarehouse (ID) not null,
RawMaterialsID int foreign key (RawMaterialsID) references RawMaterialsWarehouse (ID) not null,
RawMaterialQuantity float not null
);

Briefly:

Production: here is the product id and its quantity.

Ingredients: here is the product id for which the raw material is consumed; the raw material id; and the amount of raw material per unit of product.

RawMaterialsWarehouse: here is the total quantity of raw materials.

When Production + : all raw materials specified for this product are deducted from RawMaterialsWarehouse.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
CREATE TRIGGER Trg_Production ON Production
AFTER INSERT, UPDATE
AS

SET NOCOUNT, XACT_ABORT ON;   -- best practice to use these two

UPDATE rm
SET quantity = rm.quantity - i.Quantity
FROM
    (SELECT i.ProductsID, Quantity = i.Quantity - ISNULL(d.Quantity, 0)
    FROM inserted i
    LEFT JOIN deleted d ON d.ID = I.ID  -- for updates we take away the difference
) i
JOIN Ingredients ing ON ing.ProductsID = i.ProductsID
JOIN RawMaterialsWarehouse rm ON rm.ID = ing.RawMaterialsID
WHERE i.Quantity > 0;   --filter out zero updates

GO

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...