sql-server - 下面的存储过程有什么问题?
问题描述
alter procedure product_sales
@productid int,
@quantitysell int
as
begin
declare @productname varchar(20)
declare @quantityavailable int
select @quantityavailable=quantityav from products_trycatch
select @productname=productname from products_trycatch where productid=@productid
select @productid=productid from products_trycatch
if(not exists(select @productid from products_trycatch)
begin
raiserror('Product does not exist',16,1)
end
else
begin
if (@quantitysell>@quantityavailable)
begin
print 'Stock not available'
end
else
begin
-------------
update products_trycatch set quantityav=quantityav-@quantitysell
insert into product_log values(@productid,@productname,@quantitysell)
end
请让我知道错误在哪里。我想做的是。一个表包含一种产品的可用库存,当我执行 SP 时,我提到了正在销售的产品和数量,SP 从可用数量表中扣除该值并在新表中更新已售数量。
解决方案
你的思维非常程序化,一步一步地安排事情,但在你的几个步骤中遗漏了部分内容。
不要编写多个查询来检索单个数据。整体考虑问题1:
alter procedure product_sales
@productid int,
@quantitysell int
as
begin
declare @rc int
update products_trycatch
set quantityav = quantityav - @quantitysell
where productid = @productid and quantityav > @quantitysell
set @rc = @@ROWCOUNT
if @rc = 1
begin
insert into product_log
select @productid,productname,@quantitysell
from product_trycatch
where productid = @productid
end
else
begin
if not exists(select * from products_trycatch where productid = @productid)
begin
raiserror('Product does not exist',16,1)
end
else
begin
print 'Stock not available'
end
end
不是我的所有查询如何针对product_trycatch
匹配productid
列中的行 - 您的一些查询没有,这意味着他们将为您的变量分配非确定性值,或更新所有行product_trycatch
并扣除该@quantitysell
值。
1对于加分,我们可以编写一个update
withcase
和一个output
子句,这样就无需对product_trycatch
表中的产品名称或故障路径执行任何重新查询,但这可能不值得在这里增加额外的复杂性。此查询显示了一般技术:
declare @products table (ID int not null, Quantity int not null, Name varchar(20) not null)
insert into @products (ID,Quantity,Name) values (1,15,'Fred')
declare @ID int
declare @Qty int
declare @RefData table (OldQuantity int not null, NewQuantity int not null,
Name varchar(20) not null)
select @ID = 1, @Qty = 20
update @products
set Quantity = CASE WHEN Quantity >= @Qty THEN Quantity - @Qty ELSE Quantity END
output deleted.Quantity,inserted.Quantity, inserted.Name into @RefData
where ID = @ID
select * from @RefData
当请求的数量高于可用数量或产品存在或不存在时,您可以在其中使用@ID
和@Qty
值来查看反映的各种结果。@RefData
推荐阅读
- javascript - php 操作代码不适用于 javascript confirmAction()
- alexa - 如何使用 Alexa Skill 发出多语句请求
- excel - Excel/Powershell 从第 2 行开始循环
- python - 如何将矩阵与向量相乘,使得每一行都与该向量相乘
- python - 如何将(宽度)x(高度)命令行参数解析为两个参数?
- python - 如何根据python中的常见元素更改列表的顺序?
- java - 如何让节点等到定义拓扑
- python - Pandas DataFrame 更新列
- jquery - 如何从 URL 展开嵌套的 Bootstrap 4 Collapse?
- youtube-dl - 通过 youtube-dl 提取的 dailymotion mp4 url 不起作用