HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

writing a trigger in order to change Table Name automatically

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
triggerorderautomaticallywritingnamechangetable

Problem

Imagine there are two databases named "DB1" and "DB2".
There are two tables on both databases which are the same.
I mean we have "Table1" in "DB1" and also "Table1" in "DB2" and the data is the same as well.
I need to write a trigger so that whenever i change "Table1"'s name on "DB1", the name be changed automatically by a trigger on "DB2".
thank you.

Solution

Sys.Trigger_event_types will have all the events that can be fired.

On checking, it has an event type called RENAME. You could use that write a DDL trigger, though this may not be ideal but serves your purpose.

alter trigger  tst
on database
for
RENAME 
as 
begin

declare @oldtblname sysname,@newtablename sysname
  SELECT 
       @oldtblname= EVENTDATA().value  
        ('(/EVENT_INSTANCE/Parameters/Param)[1]','nvarchar(max)') ;

          SELECT 
       @newtablename= EVENTDATA().value  
        ('(/EVENT_INSTANCE/Parameters/Param)[2]','nvarchar(max)') ;

exec otherdbname.dbo.sp_rename @oldtblname,@newtablename;

end


There are some catches, since this is database level scoped event, this will fire for all rename events, you may want to check event type and if it is only TABLE, then you may wish to continue.

Note:

I have SQLServer 2012 and 2005 machines, this RENAME didn't worked on 2005 but worked on 2012. Not sure about 2008.

Code Snippets

alter trigger  tst
on database
for
RENAME 
as 
begin

declare @oldtblname sysname,@newtablename sysname
  SELECT 
       @oldtblname= EVENTDATA().value  
        ('(/EVENT_INSTANCE/Parameters/Param)[1]','nvarchar(max)') ;

          SELECT 
       @newtablename= EVENTDATA().value  
        ('(/EVENT_INSTANCE/Parameters/Param)[2]','nvarchar(max)') ;

exec otherdbname.dbo.sp_rename @oldtblname,@newtablename;

end

Context

StackExchange Database Administrators Q#168930, answer score: 2

Revisions (0)

No revisions yet.