日期:2014-05-18  浏览次数:20443 次

求大神赐一条sql语句,或其它解决方法
做一个采购入库:
将采购入库单中的数据查询出来,并在页面显示

问题:现在我要将这些订单中的商品的数据添加到库存表中,

要求:指定仓库如果不存在该商品,则添加商品库存,已存在商品,则修改库存数量
我怎样判断仓库中是否存在该商品呢?

采购入库表(Stocks)中有:ProID(商品编号),DepotID(仓库编号)
仓库表(Depots):DepotID

我怎样判断仓库中是否存在该商品呢?

是在页面中将库存中的所有数据查出来与采购入库单中的数据匹配吗??
还是写sql去判断???

求指教?

------解决方案--------------------
SQL code
if exists(select 1 from Stocks a,Depots b where a.DepotID=b.DepotID)
print '存在'

------解决方案--------------------
SQL code
if exists(select 1 from Stocks a,Depots b where a.DepotID=b.DepotID)
print '存在'
else 
print '不存在'

------解决方案--------------------
我觉得在数据库中判断方便
SQL code

IF EXISTS(SELECT 1 FROM 采购入库表 WHERE ProID='你要录入的商品编号' AND DepotID='你要的仓库编号' )
UPDATE 采购入库表
SET 库存数量=新库存数量
WHERE ProID='你要录入的商品编号' AND DepotID='你要的仓库编号' 
ELSE
INSERT INTO 采购入库表 VALUES(ProID,新库存数量)

------解决方案--------------------
探讨
补充一下:
还有个库存表(DepotStock):DSID(编号)、DepotID(仓库编号)、ProID(商品编号)

------解决方案--------------------
SQL code

if object_id('Stocks') is not null
   drop table Stocks
go
create table Stocks
(
 ProID varchar(10),
 DepotID varchar(10),
 SL int --数量
)
go
--创建触发器
if object_id('tr_Stocks') is not null
   drop trigger tr_Stocks
go
create trigger tr_Stocks on Stocks
for insert
as
  update b set KCSL=KCSL+a.SL from inserted a inner join DepotStock b on a.ProID=b.ProID and a.DepotID=b.DepotID
  if @@rowcount=0
     insert into DepotStock(DepotID,ProID,KCSL) select DepotID,ProID,SL from inserted
go
if object_id('DepotStock') is not null
   drop table DepotStock
go
create table DepotStock
(
 DSID int identity(1,1),
 DepotID varchar(10),
 ProID varchar(10),
 KCSL int --库存数量
)
go
insert into Stocks select '0001','01',10 --库存表中不存在,插入
insert into Stocks select '0001','02',15 --库存表中不存在,插入
insert into Stocks select '0001','01',3  --库存表中已存在,更新

select * from Stocks
select * from DepotStock
/*
三次插入语句,只有两句执行的插入操作,另一句触发器做了更新
DSID        DepotID    ProID      KCSL
----------- ---------- ---------- -----------
1           01         0001       13
2           02         0001       15

(2 行受影响)
*/