2

I am using a trigger on my table for update.

When I was updating 1 row, it works. But when I update 20 rows at once, the log only show 1 history update.

I want to show all updated rows. How to make it?

This my simple sql:

create trigger Triger_Update_Product
on product 
for update
as begin
    declare @first char(10)
    declare @after char(10)

    select @first = name from deleted

    select @after = name from inserted

    insert into historyproduk
        select @first, @after, getdate()
end
1

1 Answer 1

1

You need to write the trigger in a set-based fashion and be aware that inserted and deleted will contain multiple rows - so these lines of code are really bad:

select @first = name from deleted
select @after = name from inserted

These select one arbitrary row from the update set - and they ignore all other rows. Don't do this!!

Try this instead:

create trigger Trigger_Update_Product
on product 
for update
as begin
    insert into historyproduk
        select d.name, i.name, getdate()
        from deleted d
        inner join inserted i on d.PrimaryKey = i.PrimaryKey
end

You need to join the Inserted and Deleted pseudo tables on the primary key and then grab the Name from the old (deleted) and new (Inserted) and insert those - along with the date/time stamp - into the history table in a single INSERT ... SELECT .... statement to handle multiple rows being updated

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.