[英]How to insert a record into a table - depending on the total requiredQty from another table?
我在數據庫表中有這一行:
ID requiredQty
1088 30
另一個表:
ID orderLineID bookedInQty
3000 1088 10
3001 1088 10
dbfiddle: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=9ecd8c83fcda08453481ec6d0ce45947
概括
該特定訂單行的總預訂數量為20
和10
。
題
如何創建if
語句以將記錄插入到第二個表中,不超過表 1 requiredQty: 30
?
例子
如果插入bookedInQty: 11
這意味着它超過30
因為有一個額外的1
。 如果超過,就什么都不做。
如果插入bookedInQty: 9
這不超過30
因為總數現在等於29
。 然后插入這條記錄。
筆記
在不創建任何額外表的情況下,我嘗試使用if
語句來完成。
這使用 if 檢查 bookedQty 和新值的總和是否低於所需數量。 您可以將代碼放在存儲過程中。
create table table1(
id int NOT NULL,
requiredQty int
);
create table table2(
id int NOT NULL,
orderLineId int,
bookedInQty int
);
insert into table1(id, requiredQty) VALUES (1088, 30);
insert into table2(id, orderLineId, bookedInQty)
VALUES
(3000, 1088, 10),
(3001, 1088, 10);
declare @sumQty int, @newQty int, @newOrderLineId int;
select @newOrderLineId = 1088, @newQty = 11; -- change @newQty to 10 or lower
select @sumQty = sum(bookedInQty) from table2 where orderLineId = @newOrderLineId
group by orderLineId;
-- I hardcoded the value of id, it should add 1 to the maximum value or use an identity column
if exists(select * from table1 where id = @newOrderLineId and requiredQty >= @sumQty + @newQty)
insert table2 (id, orderLineId, bookedInQty) values (3002, @newOrderLineId, @newQty);
select * from table1;
select * from table2;
Dbfiddle 演示: https ://dbfiddle.uk/ ? rdbms = sqlserver_2019 & fiddle = d800624279381f9bbd71cf51bbc5351a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.