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 8488277
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T21:29:12+00:00 2026-06-10T21:29:12+00:00

One caveat of using the inserted and deleted tables is that they can both

  • 0

One caveat of using the inserted and deleted tables is that they can both be empty. Are there any other catchya’s I should be aware of? For instance, can the inserted table contain new records as well as updated records?

I am relying on this logic to detect the action in a trigger:

IF EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted) SET @operation = 'U'
IF EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted) SET @operation = 'I'
IF NOT EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted) SET @operation = 'D'
IF NOT EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted) SET @operation = 'X'

EDIT:

This is my solution to the audit trail problem. It has been tested on one MERGE statement that inserts, fake updates, real updates, and deletes.

ALTER TRIGGER [dbo].[LogInsertEditDelete]
ON [dbo].[<TableToAudit>]
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

--You will need to change @table to match the table to be audited
DECLARE @table VARCHAR(50)
SELECT @table = '<TableToAudit>'

-- date and user
DECLARE @updatedBy VARCHAR(50),
        @timestamp DateTime
SELECT @updatedBy = SYSTEM_USER,
       @timestamp = GETDATE()

-- Action, U = update, I = insert, D = delete
DECLARE @insertedCount int, 
        @deletedCount int
SET @insertedCount = (SELECT COUNT(*) FROM inserted)
SET @deletedCount = (SELECT COUNT(*) FROM deleted)

-- handle no action
IF @insertedCount = 0 AND @deletedCount = 0 RETURN  

-- handle update
IF @insertedCount <> 0 AND @deletedCount <> 0
BEGIN
    INSERT Audit (Type, TableName, UpdateDate, UpdatedBy, PK1)
    SELECT
        'U', 
        @table,
        @timestamp,
        @updatedBy,
        CONVERT(VARCHAR(255), i.Id)
    FROM
        (SELECT Id, BINARY_CHECKSUM(*) Version FROM inserted) i
        INNER JOIN
        (SELECT Id, BINARY_CHECKSUM(*) Version FROM deleted) d
        ON i.Id = d.Id
    WHERE
        i.Version <> d.Version  

    RETURN      
END

-- handle deletes and inserts
INSERT Audit (Type, TableName, UpdateDate, UpdatedBy, PK1)
SELECT          
    CASE 
        WHEN i.Id IS NOT NULL AND d.Id IS NULL THEN 'I'
        WHEN i.Id IS NULL AND d.Id IS NOT NULL THEN 'D'
    END,
    @table,
    @timestamp,
    @updatedBy,
    CONVERT(VARCHAR(255), COALESCE(i.Id, d.Id))
FROM inserted i 
        FULL OUTER JOIN
     deleted d 
        ON i.Id = d.Id
WHERE i.Id IS NULL OR
      d.Id IS NULL

END

This solution is not generic as the primary keys need to be spelled out for each table.

  • 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-06-10T21:29:14+00:00Added an answer on June 10, 2026 at 9:29 pm

    After making my comment I got curious as to what would be in the inserted and deleted tables in a MERGE. Here is an example:

    create table #test (test1 int identity not null, test2 varchar(34) null)
    
    
    Insert into #test (test2)
    values('test'), ('test2')
    
    select * from #test
    
    
    declare @output table(test1I int, test1D int, test2I varchar (34), test2D varchar (34))
    
    
    MERGE #test AS target
    USING (SELECT test1, test2 from #test ) AS source (test1, test2)
    ON (target.test1 = source.test1)
    WHEN MATCHED AND target.test1 = 1
        THEN UPDATE SET target.test2 = 'test3'
    WHEN  MATCHED 
        THEN DELETE
    
    OUTPUT inserted.test1, deleted.test1,  inserted.test2, deleted.test2 into @output ;
    
    select 'Inserted/deleted contents', * from @output
    select * from #test
    
    Drop table #test
    

    Something similar would happen if you were doing an insert or update.

    If you need to know for each record, you might want to use a join and a case statment to figure out the status for each record rather than using scalar variables. Remember triggers operate on the whole set of records inserted/updated/deleted not one record at a time. So the use of scalar variables is often a clue that you are not doing things correctly. If you give us more of an example of what your trigger is going to do, then it would be easier to help you solve your problem as the current approach seems as if it will not cover all records.

    Based on your comment above, perhaps this will give you some ideas on what to try within the trigger:

    Insert dbo.Audittable (Id, NewField1Value, OldField1Value, ActionTaken, ActionDate, ActionUser)
    select coalesce(inserted.id, deleted.id) as Id, inserted.field1 as newField1value, deleted.field1 as oldField1value ,
    case when inserted.id is not null and deleted.id is not null then 'Update'
    when inserted.id is not null and deleted.id is  null then 'Insert'
    when inserted.id is null and deleted.id is not null then 'Delete'
    End as ActionTaken
    , getdate() as ActionDate
    , system_user as ActionUser
    from inserted
    full outer join deleted on inserted.id = deleted.id
    

    When testing your trigger, you will need the following test cases at a minimum:

    • single record insert
    • single record delete
    • single record update
    • mulitple record insert
    • mulitple record delete
    • mulitple record update
    • mulitple record merge that does both inserts and deletes
    • mulitple record merge that does both updates and deletes
    • mulitple record merge that does both inserts and updates

    You may need more depending on everything your trigger is going to do.

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

Sidebar

Related Questions

Using Python2.4 I want to capture output from a mysql command. One caveat is
Are there any dangers/caveats one should be aware of when creating JavaScript namespaces? Our
Is there any reason why to favor using (possibly very long) CLASSPATH variable to
How do you tell if caps lock is on using JavaScript? One caveat though:
Are there any sorts of useful idioms I can make use of when writing
If you have a Form that displays data, one thing you can do is
I have two tables (A and G) in an Oracle database that can be
One of the neat characteristics of UTF-8 is that if you compare two strings
One can say a type parameter T must have a specific supertype S_1: class
One useful tip I've been using for XCode is adding breakpoints on exceptions .

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.