Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The logical tables INSERTED and DELETED cannot be updated

When I use the following statement

update INSERTED set ...

I get the following error:

The logical tables INSERTED and DELETED cannot be updated

This is the trigger code :

create trigger TCalcul
on dbo.Calcul
after insert 
  as
  begin
   set nocount on;
   declare @Num1 int;
   declare @Num2 int;
   declare @Op varchar(1);
   set @Num1 = (select Num1 from inserted)
   set @Num2 = (select Num2 from inserted)
   set @Op = (select Op from inserted)
   if @Op = '+'
    update inserted set Resultat = @Num1 + @Num2 
    else if @Op = '-'
     update inserted set Resultat = @Num1 - @Num2 ;
         else if @Op = '*'
         update inserted set Resultat = @Num1 * @Num2 ;
              else if @Op = '/'
              update inserted set Resultat = @Num1 / @Num2 ;
  end
go
like image 813
user1233875 Avatar asked Mar 16 '12 23:03

user1233875


1 Answers

As the error says you cannot change inserted. Table Calcul will already contain rows submitted by insert at the moment trigger is called; therefore you operate directly on that data. As there is a possibility of inserting multiple rows at once, you should not work with local variables but work on a set:

create trigger TCalcul
on dbo.Calcul
after insert 
as
begin

   set nocount on

   update Calcul 
          set Resultat = case Calcul.Op 
                              when '+' then Calcul.Num1 + Calcul.Num2
                              when '-' then Calcul.Num1 - Calcul.Num2
                              when '*' then Calcul.Num1 * Calcul.Num2
                              when '/' then Calcul.Num1 / Calcul.Num2
                              else null end
         from Calcul inner join Inserted on Calcul.ID = Inserted.ID
end
go

If you cannot use set for some reason then you should use cursor to step through inserted rows.

Note: I'm assuming that Calcul has a primary key named ID; you will definately need one when dealing with triggers.

EDIT:

SET NOCOUNT ON instructs Sql Server not to return a message to client saying how many row were affected by an operation. It is often used in triggers to avoid sending information which would conflict with rowcount of original query (insert, update or delete which fired the trigger). It is best to put it at the beginning of every trigger as select will also return this message.

like image 174
Nikola Markovinović Avatar answered Oct 07 '22 23:10

Nikola Markovinović