Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a need to write a SQL trigger to make Column A = Column B whenever Column A OR Column B is Updated/Changed.

Although I'm reasonably comfortable working in Management Studio, I've never written a trigger so I'm hoping someone can provide some basic guidance on how to do this and maybe with a code sample.

Any help or advice greatly appreciated,

Dana
Posted

Well of cause the trick is to understand the inserted and deleted system tables and then avoiding the recursive loop.

It can probably be done alot nicer, but this is the first version i came up with :)

create table mytable(
	id int IDENTITY(1,1) PRIMARY KEY,
	columnA nvarchar(5) ,
	columnB nvarchar(5)
	)
GO
CREATE TRIGGER [dbo].[myname]
ON [dbo].[mytable] 
FOR UPDATE
AS
BEGIN
	declare @targets table(
		id int
	)
	insert into @targets(id)
	(select id from deleted)

	declare @id int

	set @id = (select top 1 id from @targets)
	while exists(select * from @targets)
	BEGIN
		declare @a nvarchar(5)
		declare @b nvarchar(5)
		set @a = (select columnA from deleted where id = @id)
		set @b = (select columnB from deleted where id = @id)

		if (Update(columnA) or Update(columnB)) and @a <> @b
		begin
			update mytable
			set columna = columnb
			where id = @id
		end

		delete from @targets where id = @id;
		set @id = (select top 1 id from @targets)
	END
END
go

insert into mytable(ColumnA, ColumnB)
values('abc','bcd')

update mytable
set columna = 'gef'
where id = 1

select * from mytable

drop table mytable
 
Share this answer
 
It looks like you're interested in an introductory tutorial rather than help with a specific issue. In such cases, please seach the web before posting a question here.

That said, try reading Triggers -- SQL Server here on CodeProject.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900