Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Trigger Help

Author  Topic 

jbreslow
Starting Member

16 Posts

Posted - 2011-03-01 : 14:05:32
Hello,

I am trying to create a trigger to copy data from one table to a duplicate table on update. I would like this to be dynamic, so there is no need to list columns. Does anybody have a good example of this?

One part I am stuck on is comparing columns from the two different tables. How does one reference a value returned from a query?


select count(col.name) as num_columns
from sysobjects OBJ, syscolumns COL
where obj.id = col.id
and obj.name = 'USER_ADDRESS'

select count(col.name) as num_columns_multi
from sysobjects OBJ, syscolumns COL
where obj.id = col.id
and obj.name = 'USER_ADDRESS_MULTI'

-- make sure both tables have equal number of columns
if (query1.num_columns = query2.num_columns_multi){
UPDATE USER_ADDRESS_MULTI WITH CHANGES MADE TO USER_ADDRESS
}


Thank you for the help,

Josh

jbreslow
Starting Member

16 Posts

Posted - 2011-03-02 : 13:32:48
This did it... Thanks Josh!!!


-- count columns in user_address table
SELECT @ua = (
select count(col.name) as num_columns
from sysobjects OBJ, syscolumns COL
where obj.id = col.id
and obj.name = 'USER_ADDRESS')

-- count columns in user_address_multi table
select @uam = (
select count(col.name) as num_columns_multi
from sysobjects OBJ, syscolumns COL
where obj.id = col.id
and obj.name = 'USER_ADDRESS_MULTI')

IF @ua = @uam
BEGIN
print @uam
END
ELSE
BEGIN
RAISERROR ('Columns do not match, change was not committed', 11,1)
ROLLBACK
END
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2011-03-02 : 13:39:46
if you say so....

I like the part about

>> I would like this to be dynamic, so there is no need to list columns.

makes ya giggle



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page
   

- Advertisement -