日期:2014-05-18 浏览次数:20606 次
if exists(select 1 from Stocks a,Depots b where a.DepotID=b.DepotID) print '存在'
------解决方案--------------------
if exists(select 1 from Stocks a,Depots b where a.DepotID=b.DepotID) print '存在' else print '不存在'
------解决方案--------------------
我觉得在数据库中判断方便
IF EXISTS(SELECT 1 FROM 采购入库表 WHERE ProID='你要录入的商品编号' AND DepotID='你要的仓库编号' ) UPDATE 采购入库表 SET 库存数量=新库存数量 WHERE ProID='你要录入的商品编号' AND DepotID='你要的仓库编号' ELSE INSERT INTO 采购入库表 VALUES(ProID,新库存数量)
------解决方案--------------------
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 行受影响)
*/