这个触发器该怎么写?(100分)

  • 主题发起人 zhanghui127
  • 开始时间
Z

zhanghui127

Unregistered / Unconfirmed
GUEST, unregistred user!
一个表新增一条记录。其中有一个数量字段,把这个数量字段的值追加到另一个表中相同字段中。其中还有一个条件判断,决定是追加还是追减。

我的代码:
CREATE TRIGGER [Change_Number] ON [dbo].[进货表]
FOR INSERT
AS
declare @state char
declare @num int

if @@rowcount=1
begin

select @num=i.进货数量,
@state=i.状态
from inseted i
where i.日期=(select max(i.日期)from inserted i)

if @state='商品进货'
begin
update 商品信息表
set 当前库存=当前库存+@num
from 商品信息表,inserted
where 商品信息表.商品编号=inserted.商品编号
end
if @state='商品退货'
begin
update 商品信息表
set 当前库存=当前库存-@num
from 商品信息表,inserted
where 商品信息表.商品编号=inserted.商品编号
end
end


没有用,为什么?
 
这儿好像有点问题:
if @@rowcount=1
begin

select @num=i.进货数量,
@state=i.状态
from inseted i
where i.日期=(select max(i.日期)from inserted i)
去掉if @@rowcount=1呢
或去掉where i.日期=(select max(i.日期)from inserted i)
 
to cxz9,

select @num=i.进货数量,
@state=i.状态
from inseted i
笔误亚, 改为
from inserted i试试
 
CREATE TRIGGER [Change_Number] ON [dbo].[进货表]
FOR INSERT
AS
declare @state char
declare @num int

if @@rowcount=1
begin

select @num=i.进货数量,
@state=i.状态
from inseted i


if @state='商品进货'
begin
update 商品信息表
set 当前库存=当前库存+@num
from 商品信息表
where 商品信息表.商品编号=inserted.商品编号
end
if @state='商品退货'
begin
update 商品信息表
set 当前库存=当前库存-@num
from 商品信息表
where 商品信息表.商品编号=inserted.商品编号
end
end
 
还是没有用,会是哪儿出了问题呢?头晕。
 
在SQL中也可以设置类似断点ShowMessage的调试点,例如,建一个tbDebug表:
id int identity primary key notnull
data int
在你想测试的地方,写 insert into tbDebug (data) values(xxx)
例如先用这种办法判断,你的流程是否进行到了主if分支中了(在主流程中insert随便一个数),
如果进了,就判断是否进行到了应该到的分if分支,如果也进了,再分别将update以前@num和当前
库存的值以及update以后当前库存的值。这样应该找到错误了。
 
谢谢大家,问题解决。

想再问一下,为什么i.状态返回是空白,而不是返回内容,难道是中文的缘故。
 
怎么显示的“i.状态”啊?在哪里写的?怎么写的?
 
i.状态 是“商品进货“,改为 int 1就好了。
但现在又有一个问题。我第一次只能插入一条记录。如果同时插入多条记录(用缓存更新)
执行到insert into .....程序就死机了(没有出错信息)。只有先插入一条纪录后,再同时插入多条记录,
程序才能正常运行。
我再加30分,请大家帮我想想可能那儿出问题了。
 
多人接受答案了。
 
顶部