如何确定是否插入或更新

时间:2014-09-25 16:03:13

标签: sql-server triggers

每当在CUSTOMER表中发生INSERT时,我需要调用" StoredProcedure1 "和 更新发生在CUSTOMER表中,我需要调用" StoredProcedure2 "在触发器中。 如何确定是否在SQL Server 2008中插入或更新触发器

有人可以帮我解决一下吗?

代码:

CREATE TRIGGER Notifications ON CUSTOMER
FOR INSERT,UPDATE
AS
BEGIN
DECLARE @recordId varchar(20);
set @recordId= new.Id;
    //if trigger is insert at the time I call to SP1
        EXEC StoredProcedure1 @recordId
    //if trigger is Upadeted at the time I call to SP2
        EXEC StoredProcedure2 @recordId
END

5 个答案:

答案 0 :(得分:1)

让SQL Server成为SQL Server,让它为您完成工作!

为每个更改事件(插入,更新和/或删除)创建单独的触发器。 将每个逻辑放入需要它的触发器中。 无需检查事件类型。

除非快速,快速且无法阻止他人,否则不要调用程序。

答案 1 :(得分:1)

解决此问题的最简单方法是使用两个触发器,一个用于插入,另一个用于更新。

CREATE TRIGGER InsertNotifications ON CUSTOMER
FOR INSERT
AS
BEGIN
DECLARE @recordId varchar(20);
set @recordId= new.Id;
    //if trigger is insert at the time I call to SP1
        EXEC StoredProcedure1 @recordId

END

CREATE TRIGGER UpdateNotifications ON CUSTOMER
FOR UPDATE
AS
BEGIN
DECLARE @recordId varchar(20);
set @recordId= new.Id;
    //if trigger is Upadeted at the time I call to SP2
        EXEC StoredProcedure2 @recordId
END

答案 2 :(得分:1)

尝试使用此代码来触发INSERT,UPDATE和DELETE。这适用于Microsoft SQL SERVER 2008

if (Select Count(*) From inserted) > 0 and (Select Count(*) From deleted) = 0
begin
   print ('Insert...')
end

if (Select Count(*) From inserted) = 0 and (Select Count(*) From deleted) > 0
begin
   print ('Delete...')
end

if (Select Count(*) From inserted) > 0 and (Select Count(*) From deleted) > 0
begin
   print ('Update...')
end

答案 3 :(得分:0)

在INSERT上,虚拟DELETED表将为空。

答案 4 :(得分:0)

create or replace trigger comp
before
insert or delete or update
on student
referencing old as o new as n
for each row
begin
  if deleting then
           insert into student_backup values
      (:o.studid,:o.studentname,:o.address,:o.contact_no,:o.branch,sysdate);
  end if;
  if inserting then
        insert into student_backup values
      (:n.studid,:n.studentname,:n.address,:n.contact_no,:n.branch,sysdate);
 end if;
  if updating then
       insert into student_backup values
      (:o.studid,:o.studentname,:o.address,:o.contact_no,:o.branch,sysdate);
  end if;
end comp;