Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 534027
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T09:34:09+00:00 2026-05-13T09:34:09+00:00

i have what seems like a basic scenario for a db trigger in SQL

  • 0

i have what seems like a basic scenario for a db trigger in SQL server and i am running into an issue.

i have table Users (id, name, phone, etc) and i have tables UsersHistory (id, user_id action, fields, timestamp)

i want a database trigger where anytime inserts, updates or deletes into Users, i want a new record created in UsersHistory with the user id and the action that was done (insert new, updated fields, deleted id. Basically an audit log table.

this is how far i got, but i can’t figure out how to:

  1. Get the id on modify and deletes and also
  2. How to get a list of fields that have changed and the action that was committed (insert, delete, update)

CREATE TRIGGER Update_Users_History 
   ON  Users
   AFTER INSERT,DELETE,UPDATE
 AS 
 BEGIN
-- Insert statements for trigger here

insert into UsersHistory (user_id, [action], [fields], timestamp)
select  max(id) as user_id, {action ??},{fields??}  getdate() from Users)

END
GO

any suggestions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T09:34:09+00:00Added an answer on May 13, 2026 at 9:34 am

    The easiest might be to just simply create three triggers – one for each operation:

    CREATE TRIGGER trgUserInsert
    ON dbo.User AFTER INSERT
    AS BEGIN
       INSERT INTO dbo.UserHistory............
    END     
    
    CREATE TRIGGER trgUserDelete
    ON dbo.User AFTER DELETE
    AS BEGIN
       INSERT INTO dbo.UserHistory............
    END 
    
    CREATE TRIGGER trgUserUpdate
    ON dbo.User AFTER UPDATE
    AS BEGIN
       INSERT INTO dbo.UserHistory............
    END 
    

    That way, things are simple and you easily understand what you’re doing, plus it gives you the ability to turn off a trigger for a single operation, if you e.g. need to insert or delete a huge list of items.

    Inside the trigger, you have two “pseudo-tables” – Inserted (for INSERT and UPDATE) and Deleted (for UPDATE and DELETE). These pseudo tables contain the values for the newly inserted values (or the updated ones in UPDATE), or the ones that were deleted (for DELETE) or have been updated (the old values, before the update, for the UPDATE operation).

    You need to be aware that a trigger will be called once even if you update a huge number of rows, e.g. Inserted and Deleted will typically contain multiple rows.

    As a sample, you could write a “AFTER INSERT” trigger like this (just guessing what your table structure might be….):

    CREATE TRIGGER trgUserInsert
    ON dbo.User AFTER INSERT
    AS BEGIN
       INSERT INTO 
          dbo.UserHistory(UserID, Action, DateTimeStamp, AuditMessage)
          SELECT 
             i.UserID, 'INSERT', getdate(), 'User inserted into table'
          FROM
             Inserted i
    END     
    

    You are looking for a way to find out which “action” this trigger caused? I don’t see any way to do this – another reason to keep the three trigger separate. The only way to find this out would be to count the rows in the Inserted and Updated tables:

    • if both counts are larger than zero, it’s an UPDATE
    • if the Inserted table has rows, but the Deleted does not, it’s an INSERT
    • if the Inserted table has no rows, but the Deleted does, it’s a DELETE

    You’re also looking for a “list of fields that were updated” – again, you won’t have any simple solution, really. You could either just loop through the fields in the “Users” table that are of interest, and check

    IF UPDATE(fieldname) ......
    

    but that gets a bit tedious.

    Or you could use the COLUMNS_UPDATED() function – this however doesn’t give you a nice list of column names, but a VARBINARY in which each column is basically one bit, and if it’s turned on, that column was updated. Not very easy to use…..


    If you really want to create a single, big trigger, this could serve as a basis – it detects what operation has caused the trigger to fire, and will insert entries into your User_History table:

    CREATE TRIGGER trgUser_Universal
    ON dbo.Users
    AFTER INSERT, UPDATE, DELETE
    AS BEGIN
      DECLARE @InsHasRows BIT = 0
      DECLARE @DelHasRows BIT = 0
    
      IF EXISTS(SELECT TOP 1 * FROM INSERTED)
        SET @InsHasRows = 1
    
      IF EXISTS(SELECT TOP 1 * FROM DELETED)
        SET @DelHasRows = 1
    
      DECLARE @TriggerAction VARCHAR(20)
    
      IF @InsHasRows = 1 AND @DelHasRows = 1 
         SET @TriggerAction = 'UPDATE'
      ELSE
         IF @InsHasRows = 1
            SET @TriggerAction = 'INSERT'
         ELSE  
            SET @TriggerAction = 'DELETE'
    
      IF @InsHasRows = 1
        INSERT INTO dbo.UsersHistory(user_id, [action], [fields], timestamp)
          SELECT i.UserId, @TriggerAction, null, getdate()
          FROM INSERTED i
      ELSE  
        INSERT INTO dbo.UsersHistory(user_id, [action], [fields], timestamp)
          SELECT d.UserId, @TriggerAction, null, getdate()
          FROM DELETED d
    END
    

    I haven’t included the figuring out which fields have been updated part just yet – that’s left as an exercise to the reader 🙂


    Does that help at all?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 301k
  • Answers 301k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer ido-default-buffer-method may be what you are looking for, it has… May 13, 2026 at 8:08 pm
  • Editorial Team
    Editorial Team added an answer Yep, there's indeed a built-in date.future? method. May 13, 2026 at 8:08 pm
  • Editorial Team
    Editorial Team added an answer Is the release necessary? Aren't all properties already handled automatically?… May 13, 2026 at 8:08 pm

Related Questions

It seems that the choice to use string parsing vs. regular expressions comes up
I have a typical dev scenario: I have a SQL 2008 database that I
I have a question regarding the two additional columns (timeCreated, timeLastUpdated) for each record
I need a FAST decompression routine optimized for restricted resource environment like embedded systems
I always felt that expecting exceptions to be thrown on a regular basis and

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.