首页 > 解决方案 > 下面的存储过程有什么问题?

问题描述

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 从可用数量表中扣除该值并在新表中更新已售数量。

标签: sql-serverstored-procedures

解决方案


你的思维非常程序化,一步一步地安排事情,但在你的几个步骤中遗漏了部分内容。

不要编写多个查询来检索单个数据。整体考虑问题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对于加分,我们可以编写一个updatewithcase和一个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


推荐阅读