SQL Server-use table triggers to record table inserts, updates, rows deleted

Source: Internet
Author: User
Tags how to use sql

In addition to the basics of table triggers, this article also uses a bit of knowledge.

1. How to use SQL to get the current session user name and machine name
Select current_user, HOST_NAME ()
2. How to get the current table name in a table trigger
SELECT Object_schema_name (parent_id) + '.' + object_name (parent_id) from   sys.triggers

Trigger Complete code
ALTER TRIGGERDbo. Dimtest_adutittriger onDbo. Dimtest afterINSERT,DELETE,UPDATE asBEGIN                SETNOCOUNT on;Declare@tbNamevarchar(256)SELECT@tbName = ' dbo. Dimtest 'DECLARE@Action  as varchar(20), @Count int= 0;SET@Action=INSERT‘;--Set Action to Insert by default.    IF EXISTS(SELECT* fromDELETED)BEGIN        SET@Action= Case                 when EXISTS(SELECT* fromINSERTED) Then‘UPDATE‘--Set Action to Updated.                ELSE‘DELETE‘--Set Action to Deleted.             END    END    ELSE        IF  not EXISTS(SELECT* fromINSERTED)RETURN;-Nothing updated or inserted.                IF( @Action=INSERT‘or@Action=UPDATE‘)BEGIN                                Set@Count= (Select Count(*) fromINSERTED)END                IF@Action=DELETE‘BEGIN                                Set@Count= (Select Count(*) fromDELETED)END                Insert  intoDbo. AudittableSelectGETDATE (),Current_User, HOST_NAME (),NULL, @tbName, 'Dim‘,@Action,@CountENDGO

SQL Server-use table triggers to record table inserts, updates, rows deleted

Related Article

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.