How to create a trigger to insert a value into a column in the same way as the value of another column of the same table of the row just inserted in the table.
Suppose I have a table as shown below
ColumnA | ColumnB
I want the value of column B to be inserted into ColumnA as soon as the row is inserted into the table or the value of column B is updated. But this should not be the other way around, i.e. insert column value into column B
.Below code only handles INSERT, please help me how to handle how to Insert and update a table, i.e. when the value of column B is inserted or updated.
CREATE TRIGGER inserupdate ON triggertestTable AFTER INSERT,UPDATE AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for trigger here declare @value int select @value=columnB from inserted update triggertestTable set columnA=@value END GO
This works fine if the values โโinserted as shown below
insert into triggertestTable(columnB) values('xyz')
The value of column B is inserted into columnA
ColumnA | ColumnB xyz | xyz
But the null value is updated in both cases if some other application inserts the value in column A
insert into triggertestTable(columnA) values('pqr')
Now records
ColumnA | ColumnB xyz | xyz NULL | NULL
The correct record set should be as below
ColumnA | ColumnB xyz | xyz pqr | NULL
How to solve this problem.