rigger does not appear to work on multi-row updates

memberEarnings-Update.txtI have several triggers (see attachment for example) that insert a row into a change log table when updates are made to the triggered table. This seems to work quite well for single row updates, e.g. when a use changes a column value via a screen form. However, if a program updates several rows at once, either via a single query that updates multiple rows, or via individual queries executed in a programatic 'for' loop, it seems that only one row gets inserted into the log table, not one for each update.

What's up with this? Do I have to put some kind of seeing on the table or database or is this not doable?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lcohanDatabase AnalystCommented:
You must change your triggers to deal with batch operations and you should use INSERTED and DELETED tables for this matter than for multiple rows in any of these two internal tables write a batch operation - I recommend do NOT use cursors in triggers as they can have pretty big negative performance hit.
lcohanDatabase AnalystCommented:
In the trigger you can use following code to see if there are multiple or single rows affected:

--then you must write trigger action for batch operation
--single row affected

Same thing for DELETED table on DELETE trigger action.
(Not for points --) In case it's not clear, there will be a temporary table named "INSERTED" when an INSERT trigger fires. The trigger can reference the rows in the table named INSERTED if the trigger needs to know that multiple rows were inserted. There will be one row in the INSERTED table for each row that was inserted. The format of the INSERTED table will always match whatever table the trigger is defined over.

For a DELETE trigger, there will be a temporary table named DELETED. It can be used pretty much the same way an INSERTED table would be used.

Basically, the trigger would put a row into the change log for every row in the INSERTED (or the DELETED) table.

IT Pros Agree: AI and Machine Learning Key

We’d all like to think our company’s data is well protected, but when you ask IT professionals they admit the data probably is not as safe as it could be.

MarkAuthor Commented:
Here's a fragment of the code I have now:

if UPDATE(earningCode) begin
    select @memberId = memberId from DELETED
    select @oldVal = case when earningCode is null then '' else earningCode end from DELETED
    select @recId = recId from DELETED
    select @newVal = case when earningCode is null then '' else earningCode end from INSERTED

  if @oldVal <> @newVal
    INSERT INTO changeLog (tableName,columnName,userName,changeTime,memberId,keyField,oldValue,newValue)
      values ('memberEarnings','earningCode',@uname,getdate(),@memberId,@recId,@oldVal,@newVal)

Open in new window

This code assumes 1 change, as you all have mentioned. How would I transform this to loop through updates? What's the syntax for looping through updates, FETCH NEXT FROM INSERTED ... ? How would I retrieve the corresponding DELETED row?
lcohanDatabase AnalystCommented:
Something liek code below but please double chek the code and test first!
Create Trigger  [test].[table_upd]
 On [test].[table]

declare @memberid int
declare @oldval int
declare @newval int
declare @recid int
declare @uname sysname

if UPDATE(earningCode) AND (select count(*) from inserted) = 1
begin -- single insert

    select @memberId = memberId from DELETED
    select @oldVal = case when earningCode is null then '' else earningCode end from DELETED
    select @recId = recId from DELETED
    select @newVal = case when earningCode is null then '' else earningCode end from INSERTED

  if @oldVal <> @newVal
    INSERT INTO changeLog (tableName,columnName,userName,changeTime,memberId,keyField,oldValue,newValue)
      values ('memberEarnings','earningCode',@uname,getdate(),@memberId,@recId,@oldVal,@newVal)
end --single insert

if UPDATE(earningCode) AND (select count(*) from inserted) > 1
declare @loop_table table (recId int)
insert into @loop_table select recId from inserted union select recId from deleted

while (select count(*) from @loop_table) > 0
begin -- loop
    set @recId = (select top 1 id from @loop_table order by id)

    select @memberId = memberId from DELETED where recid = @recId
    select @oldVal = case when earningCode is null then '' else earningCode end from DELETED where recid = @recId
    select @newVal = case when earningCode is null then '' else earningCode end from INSERTED where recid = @recId
    select @recId = recId from DELETED where recid = @recId
      if @oldVal <> @newVal
            INSERT INTO changeLog (tableName,columnName,userName,changeTime,memberId,keyField,oldValue,newValue)
            values ('memberEarnings','earningCode',@uname,getdate(),@memberId,@recId,@oldVal,@newVal)

end -- loop
lcohanDatabase AnalystCommented:
OOOPs..Missed the delete so it would be a endless loop - please add followinfg line just before the end -- loop:

   delete from @loop_table where recid = @recid -- this is to removed processed row and skip to next
Scott PletcherSenior DBACommented:
It's fastest to use set-based statements in SQL Server, like below.

I wasn't 100% of the values to use in the COALESCEs in the WHERE clause, so you may have to adjust those.

/****** Object:  Trigger [dbo].[memberEarnings_Update]    Script Date: 03/16/2012 10:48:22 ******/
/* trigger: memberEarnings_Update
    author: Mark Foley - Novatec Software Engineering, LLC - mfoley@novatec-inc.com
      date: 05-DEC-2011

 This trigger logs changes made to the memberEarnings table.

ALTER TRIGGER [dbo].[memberEarnings_Update]
ON [dbo].[memberEarnings]

declare @uname varchar(30)
declare @ix integer


set @uname = suser_sname()
set @ix = charindex('\',@uname)
set @uname = substring(@uname,@ix + 1, len(@uname) - @ix)
if @uname = 'webuser' set @uname = host_name()

-- will only insert for a change to one of these columns:
--   'earningCode', 'amount', 'enabled', and 'oneShot'.
-- every column change is inserted separately:
INSERT INTO dbo.changeLog (tableName,columnName,userName,changeTime,memberId,keyField,oldValue,newValue)
    'memberEarnings', column_name, @uname, getdate(), i.memberId,
    CASE column_name
        WHEN 'earningCode' THEN CAST(d.keyId AS varchar(11))
        ELSE earningCode END AS keyField,    
    CASE column_name
        WHEN 'earningCode' THEN CAST(d.earningCode AS varchar(80))
        WHEN 'amount'      THEN CAST(d.amount      AS varchar(80))
        WHEN 'enabled'     THEN CAST(d.enabled     AS varchar(80))
        WHEN 'oneShot'     THEN CAST(d.oneShot     AS varchar(80))
    END AS oldValue,
    CASE column_name
        WHEN 'earningCode' THEN CAST(i.earningCode AS varchar(80))
        WHEN 'amount'      THEN CAST(i.amount      AS varchar(80))
        WHEN 'enabled'     THEN CAST(i.enabled     AS varchar(80))
        WHEN 'oneShot'     THEN CAST(i.oneShot     AS varchar(80))
    END AS newValue
FROM inserted i
INNER JOIN deleted d ON
    d.recId = i.recId
    SELECT 'earningCode' AS column_name WHERE UPDATE(earningCode) UNION ALL
    SELECT 'amount' WHERE UPDATE(amount) UNION ALL
    SELECT 'enabled' WHERE UPDATE(enabled) UNION ALL
    SELECT 'oneShot' WHERE UPDATE(oneShot)
) AS column_names
    (column_name = 'earningCode' AND COALESCE(d.earningCode, '') <> COALESCE(i.earningCode, '')) OR
    (column_name = 'amount'      AND COALESCE(d.amount     , 0)  <> COALESCE(i.amount, 0))       OR
    (column_name = 'enabled'     AND COALESCE(d.enabled    , 0)  <> COALESCE(i.enabled, 0))      OR
    (column_name = 'oneShot'     AND COALESCE(d.oneShot    , '') <> COALESCE(i.oneShot, ''))      

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MarkAuthor Commented:
Hmmm, these already messy solutions can get even messier with tables having more columns. I think I'll stick with the single row update in the trigger. If I want to log multiple updates, I'll change my program to loop through the table records.
MarkAuthor Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.