首页 > 代码库 > 建立触发器后,不能像表中插入数据,是什么原因

建立触发器后,不能像表中插入数据,是什么原因

建立触发器后,不能像表中插入数据,是什么原

USE [cai2016]
GO
/****** Object:  Trigger [dbo].[trigger_yunum]    Script Date: 2017/3/29 17:30:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter trigger [dbo].[trigger_yunum]
  on [dbo].[newmoo_case_cgxd]
   for  insert
  as
    BEGIN

    DECLARE @id bigint SELECT @id = id FROM INSERTED
    DECLARE @purchase_id varchar SELECT @purchase_id = purchase_id FROM INSERTED
    DECLARE @slength nvarchar SELECT @slength = slength FROM INSERTED
    DECLARE @engname nvarchar SELECT @engname = engname FROM INSERTED

    DECLARE @swidth nvarchar SELECT @swidth = swidth FROM INSERTED
    DECLARE @kehu_id bigint SELECT @kehu_id = kehu_id FROM INSERTED
    DECLARE @caseid bigint select @caseid =caseid FROM INSERTED
    DECLARE @productnum int SELECT @productnum = productnum FROM INSERTED
    DECLARE @pay numeric SELECT @pay = pay FROM INSERTED
    DECLARE @costprice numeric SELECT @costprice = costprice FROM INSERTED


    DECLARE @pid_p bigint select @pid_p =pid_p FROM INSERTED
    DECLARE @cz int SELECT @cz = cz FROM INSERTED
    DECLARE @productRemarks nvarchar SELECT @productremarks = productremarks FROM INSERTED
    DECLARE @weight numeric SELECT @weight = weight FROM INSERTED
    
    Update  a set a.overnum=(select a.id, a.overnum, a.oknum, a.yunum, b.caseid, b.productnum, b.ischeck, sum(b.productnum)  from newmoo_case a, newmoo_case_cgxd b where b.caseid=a.id and b.ischeck=3)
     

end

use test
go
-- 表1(id,productnum),建立几个测试数据
if object_id(‘表1‘) is null
begin
  create table 表1(id int,productnum numeric(10,2))
  insert into 表1
  select 1001,10.5 union all
  select 1001,20.5 union all
  select 1001,30.5 union all
  select 1001,30.5 union all
  select 1002,20.2 union all
  select 1002,30.2
end
-- select * from 表1

-- 表2(id,overnum,upd),建立几个测试数据,汇总表
if object_id(‘表2‘) is null
begin
  create table 表2(id int,overnum numeric(10,2),upd datetime )
  insert into 表2
  select 1001,0.0,getdate() union all
  select 1002,0.0,getdate()
end
-- select * from 表2
go


-- 上面的是测试数据,下面开始建立 触发器 

alter trigger [dbo].[tr_表1] --第1次运行时,create,
on [dbo].[表1]
for insert
as
begin
  declare @id int
  select @id=id from inserted

  update a set a.overnum=b.productnum,upd=getdate() 
  from 表2 a,(select id,productnum=sum(productnum) from 表1 where id=@id group by id) b
  where a.id=b.id
end

go

-- 测试往“表1”插入数据,看表2是否更新,查看前后变化
select * from 表2
go
insert into 表1(id,productnum) values(1002,30.5)
select * from 表2

建立触发器后,不能像表中插入数据,是什么原因