Use a cursor to add a trigger with the same structure to each user table in the database

Source: Internet
Author: User
-- Add a log_mode field to each table in the synchroflow_log database.
Use synchroflow_log
Exec sp_msforeachtable 'alter table? Add log_mode char (2 )'

-- Create a mainmoniter table
Create Table mainmoniter (mode char (2), tablename varchar (50), changetime char (20 ))


-- Inserts the table name in the synchroflow database into a temporary table.
Select name into # TT from sysobjects where (type = 'U ')


Use synchroflow
-- Defines the cursor and creates a trigger for each table through the cursor
Declare @ table_name varchar (100)

Declare cursor_temp cursor for select name from # TT

Open cursor_temp

Fetch next from cursor_temp into @ table_name

While @ fetch_status = 0
Begin
Declare @ SQL _a varchar (1000)
Declare @ SQL _u varchar (1000)
Declare @ SQL _d varchar (1000)

Set @ SQL _a = 'create trigger' + @ table_name + '_ A on' + @ table_name + 'For insert as insert into synchroflow_log.dbo. '+ @ table_name + 'select *, ''a' as log_mode from inserted insert into synchroflow_log.dbo.mainmoniter select ''a', ''' + @ table_name + ''', convert (char (19), getdate (), 120) from inserted'

Set @ SQL _u = 'create trigger' + @ table_name + '_ u on' + @ table_name + 'for update as insert into synchroflow_log.dbo. '+ @ table_name + 'select *, ''u'' as log_mode from deleted insert into synchroflow_log.dbo.mainmoniter select ''u'', ''' + @ table_name + ''', convert (char (19), getdate (), 120) from deleted'

Set @ SQL _d = 'create trigger' + @ table_name + '_ d on' + @ table_name + 'For Delete as insert into synchroflow_log.dbo. '+ @ table_name + 'select *, ''d' as log_mode from deleted insert into synchroflow_log.dbo.mainmoniter select ''d', ''' + @ table_name + ''', convert (char (19), getdate (), 120) from deleted'

Exec (@ SQL _a)
Exec (@ SQL _u)
Exec (@ SQL _d)
Fetch next from cursor_temp into @ table_name
End

Close cursor_temp
Deallocate cursor_temp

-- Delete a temporary table
Drop table # TT

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.