--进出货,存储过程的应用实例
create database mydb --创建数据库
go
use mydb --连接数据库
go
--水果表
create table Fruit
(
Ids varchar(50) primary key,
[Name] varchar(50) not null,
Price decimal(8,2),
Source varchar(50),
Stack varchar(50),
Numbers int, --库存数量
[Image] varchar(50)
)
go
insert into fruit values('k001','苹果',2.4,'烟台','2',100,'image/0.gif')
insert into fruit values('k002','菠萝',1.4,'广东','3',100,'image/1.gif')
insert into fruit values('k003','桔子',2.4,'福州','3',100,'image/2.gif')
insert into fruit values('k004','葡萄',2.4,'新缰','2',100,'image/3.gif')
insert into fruit values('k005','樱桃',2.4,'青岛','4',100,'image/4.gif')
insert into fruit values('k006','桃子',2.4,'花果山','5',100,'image/5.gif')
insert into fruit values('k007','香蕉',2.4,'济南','5',100,'image/6.gif')
--用户表
create table Login
(
UserName varchar(50) primary key, --用户名
[Name] varchar(50), --真实姓名
Password varchar(50), --密码
Account decimal(18,2) --账户余额
)
go
insert into login values('zhangsan','张三','666666',50)
insert into login values('lisi','李四','666666',50)
insert into login values('wangwu','王五','666666',50)
--订单表
create table Orders
(
Code varchar(50) primary key, --以“用户名yyyyMMddhhmmssms”的形式作主键
UserName varchar(50) references Login(Username), --订购人员代号
OrderTime datetime, --订购时间
)
go
--订单内容表
create table OrderDetails
(
Ids int identity primary key,
OrderCode varchar(50) references Orders(Code),--订单号
FruitCode varchar(50) references Fruit(Ids),--水果代号
[Count] int , --水果的个数
)
go
select * from fruit
select * from login
select * from orders
select * from orderdetails
----进销存存储过程
use mydb
go
select*from Fruit
create proc jinchuhuo --创建存储过程
@ids varchar(50),--输入参数
@name varchar(50),
@price decimal(8,2),
@source varchar(50),
@stack int,
@numbers int,--正数进货,负数出货
@image varchar(50)
as
if @numbers>0 --正数则执行以下操作
begin
declare @shuliang1 int --声明一个变量,来接收查询结果
select @shuliang1=COUNT(*)from Fruit where ids=@ids--查询库中有木有这种水果
if @shuliang1>0--有,修改数据库
begin
declare @shuliang3 int--声明一个变量,来接收查询结果
select @shuliang3=Numbers from Fruit where Ids=@ids --查询这种水果有多少
update Fruit set Numbers=Numbers+@numbers where Ids=@ids --修改表
print '已修改库存,现有存货'
return @shuliang3+@numbers --返回值
end
else--木有这种水果,则插入这条新的信息
begin
insert into Fruit values(@ids,@name,@price,@source,@stack,@numbers,@image)
print '已经新增进货数据,现有库存'
return @numbers --返回值
end
end
else --小于0,则出货
begin
declare @shuliang2 int
select @shuliang2=COUNT(*)from Fruit where ids=@ids--查询库中有木有这种水果
if @shuliang2>0
begin
declare @shuliang4 int
select @shuliang4=Numbers from Fruit where Ids=@ids
if @shuliang4>ABS(@numbers) --库存数量足够,则出库,修改数据库
begin
update Fruit set Numbers=Numbers+@numbers where Ids=@ids
print '出货成功,剩余库存'
return @shuliang4+@numbers --返回值
end
else
begin
print '库存数量不足,现有库存'
return @shuliang4 --返回值
end
end
else
begin
print '木有这种水果,木法出货'
end
end
go
select*from Fruit
declare @a int --声明一个变量,来接收存储过程jinchuhuo的返回值
exec @a=jinchuhuo 'k009','西瓜','3.7','青州','2','-100','image/7.gif' --输入参数
print @a --显示返回值