How to determine if insert or update

与世无争的帅哥 提交于 2019-12-28 06:56:07

问题


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 "StoredProcedure2" in the Trigger. How to determine if insert or update in the trigger from SQL Server 2008.

Some one can please help me how to solve?

Code:

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

回答1:


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.




回答2:


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



回答3:


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



回答4:


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




回答5:


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;


来源:https://stackoverflow.com/questions/26043106/how-to-determine-if-insert-or-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!