sql server - Update trigger that affects only modified columns -
i trying create trigger update columns if value has been changed. i've read done comparing inserted , deleted tables. below how i'm trying comparison.
is there other way? think select
queries , if
statements can nested in ways, can't figure out how.
create trigger [dbo].[tr_persoane_update] on [dbo].[persoane] after update begin set nocount on; declare @dfirstname varchar(30), @ifirstname varchar(30), @dlastname varchar(30), @ilastname varchar(30) select @dfirstname=d.firstname, @dlastname=d.lastname deleted d select @ifirstname=i.firstname, @ilastname=i.lastname inserted if @dfirstname <> @ifirstname begin update firstname set firstname = @ifirstname firstname = @dfirstname end if @dlastname <> @ilastname begin update lastname set lastname = @ilastname lastname = @dlastname end end
i tried approach, fail use case statement properly.
alter trigger [dbo].[tr_persons_update] on [dbo].[persons] after update begin set nocount on; select d.firstname, d.lastname, d.id_title, i.firstname, i.lastname, i.id_title, case when d.firstname <> i.firstname begin update persons set firstname = i.firstname firstname = d.firstname print 'firstname modified' end /*end case*/ when d.lastname <> i.lastname begin update persons set lastname = i.lastname lastname = d.lastname print 'lastname modified' end /*end case*/ when d.id_title <> i.id_title begin update persons set id_title=i.id_title id_title=d.id_title end end deleted d inner join inserted on d.id_person=i.id_person end
here example first name:
update fn set firstname = id.newfname firstname fn join (select i.firstname newfname, d.firstname oldfname inserted join deleted d on i.personid = d.personid i.firstname <> d.firstname ) id on fn.firstname = id.oldname;
you shouldn't assume inserted
, deleted
contain 1 value. requires id
matches 2 view (inserted
, deleted
views , not tables).
Comments
Post a Comment