Link to home
Start Free TrialLog in
Avatar of natejacobs
natejacobs

asked on

Update Trigger

I need an update trigger that fires after update which will look at my QuantityOrdered and QuantityDelivered fields and set a UserID field to SUser_SName() if they're equal.

Anyone?
Avatar of Hilaire
Hilaire
Flag of France image

Thsi kind of code should do the trick

create trigger utg_yourtable_upd on yourtable
for update
as
if update(QuantityDelivered) or update(QuantityOrdered )
begin
update a
set UserID = SUser_SName()
from yourtable a
inner join inserted i on a.primarykey = i.primarykey
where i.QuantityOrdered  = i.QuantityDelivered
end
Of course you'll need to replace "yourtable" and "primarykey"
with your actual table name and it's primary key column name(s) (might be a composite key)
Avatar of obahat
obahat

CREATE TRIGGER [dbo].[MyTrigger] ON [dbo].[MyTable] AFTER UPDATE
AS
BEGIN
    UPDATE [dbo].[MyTAble]
    SET [UserID] = SUser_SName()
    FROM [dbo].[MyTAble] a
          INNER JOIN [Inserted] i
            ON a.[PKColumns] = i.[PKColumns]
   WHERE i.[QuantityOrdered] = i.[QuantityDelivered]
            ON a.[DeviceNumber] = i.[DeviceNumber]
END
Avatar of natejacobs

ASKER

What I really need to do is increase the QuantityDelivered by 1 on an update SP

UPDATE  
     MyTable
SET          
     QuantityDelivered = QuantityDelivered +1
WHERE    
     MyTablePK = @ID

Then I need to check the 2 columns (QuantityOrdered, QuantityDelivered) to see if they're equal.
If they are equal, I need to set the EmployeeID.

Ideas?
Then this should do the trick

UPDATE  
     MyTable
SET          
     UserID = case
            when QuantityDelivered + 1 = QuantityOrdered then SUser_SName()
           else UserID
     end,
     QuantityDelivered = QuantityDelivered +1,
WHERE    
     MyTablePK = @ID

Shouldn't QuantityDelivered be incremented first? - and then the UserID updated if QuantityDelivered  =  QuantityOrdered ?  

I only want to set the userID field to SUser_SName() IF the two fields are equal after QuantityDelivered has been updated.

Of course I could be missing your point, too  :)
ASKER CERTIFIED SOLUTION
Avatar of Hilaire
Hilaire
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial