--模拟环境表与数据
/*
通过销售单号查找到销售明细中的产品,通过查询语句判断该明细中的产品是否在库存中充足,如果每一个产品都充足,则一次性扣除,有一个不足则不扣除。
测试通过,未在生产环境中实验。
*/
CREATE TABLE [dbo].[ssmx](
[ssdh] [int] NULL,
[cpid] [varchar](5) NULL,
[sl] [int] NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[ss](
[ssdh] [int] NULL,
[ckzt] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[kc](
[id] [varchar](5) NULL,
[sl] [int] NULL
) ON [PRIMARY]
INSERT [dbo].[ssmx] ([ssdh], [cpid], [sl]) VALUES (1512150001, N‘10001‘, 100)
INSERT [dbo].[ssmx] ([ssdh], [cpid], [sl]) VALUES (1512150001, N‘10002‘, 400)
INSERT [dbo].[ssmx] ([ssdh], [cpid], [sl]) VALUES (1512150002, N‘10003‘, 100)
INSERT [dbo].[ssmx] ([ssdh], [cpid], [sl]) VALUES (1512150002, N‘10002‘, 200)
INSERT [dbo].[ss] ([ssdh], [ckzt]) VALUES (1512150001, 0)
INSERT [dbo].[ss] ([ssdh], [ckzt]) VALUES (1512150002, 0)
INSERT [dbo].[kc] ([id], [sl]) VALUES (N‘10001‘, 100)
INSERT [dbo].[kc] ([id], [sl]) VALUES (N‘10002‘, 500)
INSERT [dbo].[kc] ([id], [sl]) VALUES (N‘10003‘, 200)
--创建存储过程,自动出库
--入参销售单号
create proc zdck(@ssdh int)
as
begin
declare @count int=0;
select t2.* into #ssmx from ss t1 inner join ssmx t2 on t1.ssdh=t2.ssdh where [email protected] and t1.ckzt=0;
select @count=COUNT(1) from #ssmx;
if @count>0
begin
declare @kccount int=0;
select @kccount=COUNT(1) from kc t1 inner join ssmx t2 on t1.id=t2.cpid where [email protected];
if @[email protected]
begin
declare @zg int=0;--库存是否足够减
select @zg=sum(case when t1.sl-t2.sl>=0 then 1 else 0 end) from kc t1 inner join ssmx t2 on t1.id=t2.cpid
where [email protected] group by t2.ssdh
print ‘zg‘+cast(@zg as varchar(100));
if @[email protected]
begin
update kc set sl=t1.sl-t2.sl from kc t1 inner join ssmx t2 on t1.id=t2.cpid
where [email protected];
update ss set ckzt=1 where [email protected];
end
end
end
end
--开始测试
--查看原始库存表
select * from kc
10001 100
10002 500
10003 200
--销售表 0表示该销售单未出库
--两张销售单
select * from ss
1512150001 0
1512150002 0
--销售明细表
select * from ssmx
1512150001 10001 100
1512150001 10002 400
1512150002 10003 100
1512150002 10002 200
--执行存储过程
--尝试 1512150001 单据出库
exec zdck 1512150001
--销售表ckzt=1 表示出库成功
select * from ss
1512150001 1
1512150002 0
--查看库存相应产品的数量减掉
select * from kc
10001 0
10002 100
10003 200
--执行存储过程
--尝试 1512150002 单据出库
exec zdck 1512150002
--查看库存相应产品的数量减掉
--查看库存数量未变
select * from kc
--查看1512150002销售单号的出库情况,ckzt还是0
select * from ss where ssdh=1512150002
--删除测试表及存储过程
drop table ssmx;
drop table ss;
drop table kc;
drop proc zdck;