Quantcast
Viewing all articles
Browse latest Browse all 23857

Creating DDL trigger to keep two identical tables on two separate databases, keeping their columns in same order and in sync

I have two databses, tempdblog and testdblog. I'm trying to figure out how, when i alter a table on tempdblog, that exact same command will be executed on testdblog, i don't want the rows transfered i strictly want the columns.

Below is what i have atm from a site, i've tried to add a "USE testdblog" but it errors back at me about "a USE statement is not allowed..." as well as "must declare the scalar variable @test".

The new column names could be anything, all i know is that it's not a "add this column to the end of the table", it's more like "add this column just before userdef0 column".

I store the SQL query it did on the main database and try to re-execute it on the other table, it's just a matter of finding out how to change databases.

USE tempdblog
GO
ALTER TRIGGER [db_LOG]
ON DATABASE
FOR CREATE_TABLE,DROP_TABLE,ALTER_TABLE
AS
      SET NOCOUNT ON
      DECLARE @xEvent XML
      DECLARE @test varchar(5000)
      SET @xEvent = eventdata()
      SET @test = CONVERT(VARCHAR(MAX), @xEvent.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)'))
      INSERT INTO dbLOG VALUES(
            REPLACE(CONVERT(VARCHAR(50), @xEvent.query('data(/EVENT_INSTANCE/PostTime)')),'T', ' '),
            CONVERT(VARCHAR(25), @xEvent.query('data(/EVENT_INSTANCE/ServerName)')),
            CONVERT(VARCHAR(15), @xEvent.query('data(/EVENT_INSTANCE/UserName)')),
            CONVERT(VARCHAR(MAX), @xEvent.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)'))
            )   
      USE testdblog
      GO
      exec sp_executesql @test
GO



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>