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

Posted 咸蛋超哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建立触发器后,不能像表中插入数据,是什么原因相关的知识,希望对你有一定的参考价值。

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

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 [email protected] 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

以上是关于建立触发器后,不能像表中插入数据,是什么原因的主要内容,如果未能解决你的问题,请参考以下文章

怎么用SQL语句同步两个表中的字段值?

SQL数据库中一个表突然不能修改和插入,怎么解决?

建立 SQLSERVER 触发器 在一个服务器上的数据库中插入数据时同时插入到另一个服务器上的数据库的表中

完成表中的数据插入后如何触发触发器

sqlserver2005触发器问题

触发器处理表更新