How to determine if insert or update

后端 未结 5 681
庸人自扰
庸人自扰 2020-12-07 00:03

Whenever INSERT is happened in the CUSTOMER table,I need to call the \"StoredProcedure1\"and UPDATE is happend in the CUSTOMER table,I need to call the \"

相关标签:
5条回答
  • 2020-12-07 00:23

    Try this code for trigger for INSERT, UPDATE and DELETE. This works fine on 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
    
    0 讨论(0)
  • 2020-12-07 00:33
    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;
    
    0 讨论(0)
  • 2020-12-07 00:35

    The easiest way to solve this problem would be to have two triggers, one for the insert and one for the update.

    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
    
    0 讨论(0)
  • 2020-12-07 00:46

    On an INSERT, the virtual DELETED table will be empty.

    0 讨论(0)
  • 2020-12-07 00:48

    Let SQL Server be SQL Server, and have it do the work for you!

    Create separate triggers for each change event (insert,update and/or delete). Put the logic for each into the trigger that needs it. No need to have to check for the event type.

    And don't call a procedure unless it is quick, fast, and can't block others.

    0 讨论(0)
提交回复
热议问题