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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With