Create trigger to insert a column value into other column of same table SQL Server 2005 -
how create trigger insert value in column same value of column of same table of newly inserted row in table.
suppose have table below
columna | columnb
i want columnb value inserted columna row gets inserted table or columnb value gets updated . should not vice versa ie insert columna value columnb
.below code handles insert , please me how handle both insertion , updation of table ie when columnb value gets inserted or updated.
create trigger inserupdate on triggertesttable after insert,update begin -- set nocount on added prevent result sets -- interfering select statements. set nocount on; -- insert statements trigger here declare @value int select @value=columnb inserted update triggertesttable set columna=@value end go
this works fine if values inserted below
insert triggertesttable(columnb) values('xyz')
columnb value gets inserted columna
columna | columnb xyz | xyz
but null value gets updated in both if other application inserts value in columna
insert triggertesttable(columna) values('pqr')
now records are
columna | columnb xyz | xyz null | null
the correct recordset should below
columna | columnb xyz | xyz pqr | null
how solve problem.
try trigger (it copy values columnb columna when inserted values columnb or when updated values columbb):
create trigger trgiu_triggertesttable_updatecolumnawhencolumnb on dbo.triggertesttable after insert,update begin -- set nocount on added prevent result sets -- interfering select statements. set nocount on; if update(columnb) begin update dbo.triggertesttable set columna=i.columnb inserted inner join dbo.triggertesttable t on i.myid=t.myid left join deleted d on i.myid=d.myid d.myid null , i.columnb not null -- row inserted or d.myid not null -- row updated end end go
i used table:
create table dbo.triggertesttable( myid int identity(1,1) primary key, -- myid should primary key or mandatory(not null) unique constraint columna varchar(100), columnb varchar(100) ); go
Comments
Post a Comment