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?
Anyone?
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)
with your actual table name and it's primary key column name(s) (might be a composite key)
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
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
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?
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
UPDATE
MyTable
SET
UserID = case
when QuantityDelivered + 1 = QuantityOrdered then SUser_SName()
else UserID
end,
QuantityDelivered = QuantityDelivered +1,
WHERE
MyTablePK = @ID
ASKER
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 :)
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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