我在数据库表中有这一行:
ID requiredQty
1088 30另一张桌子:
ID orderLineID bookedInQty
3000 1088 10
3001 1088 10dbfiddle:
摘要
总预订量是为该特定订单行剩余的20和10的总数。
问题
如何创建if语句以将记录插入到第二个表中,而不超过表1 requiredQty: 30
示例
如果插入bookedInQty: 11,这意味着它超过了30,因为有一个额外的1。如果它超过了,就什么也不做。
如果要插入bookedInQty: 9,这不会超过30,因为总数现在等于29。然后插入此记录。
Note
在不创建任何额外表的情况下,我尝试使用if语句来实现它。
发布于 2020-10-05 17:46:00
这使用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
https://stackoverflow.com/questions/64213158
复制相似问题