How to Edit Values of an Insert in a Trigger on SQL Server

How can I edit values of an INSERT in a trigger on SQL Server?

Use an after insert trigger. Join from the inserted pseudo table to Tb on the primary key. Then update the values of desc. Something like: (But may not compile)

CREATE TRIGGER TbFixTb_Trg 
ON Tb
AFTER INSERT
AS
BEGIN
UPDATE Tb
SET DESC = SomeTransformationOf(i.DESC)
FROM Tb
INNER JOIN inserted i on i.Id = Tb.Id
END
GO

This trigger happens after the insert has happened, but before insert statement completes. So the new, incorrect values are already placed in the target table. This trigger will not need to change as columns are added, deleted, etc.

Caveat Integrity constraints are enforced before the after trigger fires. So you can't put on a check constraint to enforce the proper form of DESC. Because that would cause the statement to fail prior to the trigger having a chance to fix anything. (Please double check this paragraph before relying on it. It's been awhile since I've written a trigger.)

Change value of inserted row's column with trigger

Your first mistake is to assume single row insert only. All DML operations are set operations. So if you want to update something work with sets.

CREATE TRIGGER [dbo].[TR_FixBatchTimes_I]
ON [dbo].[HEADER_BAT]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
update HEADER_BAT
set F908='0000', F910=2359, F914='WAIT'
from HEADER_BAT h
inner join inserted i on h.id = i.id --or what is PK
where i.F916 = 'FSPRICE_BAT'
END

Update Trigger, set value for the inserted data SQL Server

Your trigger has many issues, it doesn't use the real table you want to update, it assumes only one row is modified every time, and the logic with the RETURN is too weird.

CREATE TRIGGER dbo.trgIssueAcknowledged 
ON dbo.hdIssues
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

UPDATE A
SET A.AcknowledgeDate = GETDATE()
FROM dbo.hdIssues A
INNER JOIN INSERTED I
ON A.TheKeyOfTheTable = I.TheKeyOfTheTable
WHERE A.AcknowledgeDate IS NULL
AND ( A.AssignedToUserID <> 0 AND A.AssignedToUserID IS NOT NULL)

END

How to compare and update an inserted value to existing value using a trigger?

Re your (now edited out) question about :old and :new - old and new are most applicable to update queries where they allow you to examine the before-update and after-update value of the same row - the scenario you're discussing is one of editing a different row using an insert so :old doesn't really apply - the insert trigger will only have a :new pseudorow. There wouldn't be an :old that refers to a different row existing in the table


Two ways you could do this with a "before insert" trigger - either:

  • find the existing row and if it exists, copy its data into the :new row then delete the existing row. This is an errorless way of handling the issue but is perhaps longer to code
  • issue an update query to update an existing row and if a row is updated, raise an application error to prevent the insert of the new row

For a discussion on before insert triggers that prevent inserts in some scenarios see Prevent Insert Trigger - and expect some said "don't use triggers" chatter; it's good advice. Every time I've used triggers a part of me wishes I hadn't :)

ps; I specifically haven't written the code for this for you because you've said it's a learning exercise, but if you feel you'll learn more by reading code from someone else rather than writing it out yourself, let me know and I'll provide some example. Tejash has made a reasonable start on the update route i describe, it just remains to use the sql%rowcount to know how many rows were updated and raise an exception to prevent the insert

SQL use trigger during insert for calculating value in one table

As you mentioned, what you want to do is:

  • Create a trigger
  • Establish when it should trigger - Insert & update
  • Create a function which runs each time an update or insertion is made

Please be aware that I am only experienced with PL/pgSQL (PostgresSQL), so that's the language of the function.

Creating a trigger

CREATE TRIGGER insertOrder    
AFTER INSERT OR UPDATE ON Orders
FOR EACH ROW
EXECUTE PROCEDURE functionSetOrderPrice();

This trigger is called insertOrder, and will trigger the function "functionSetOrderPrice()" whenever we insert or update a row in the Orders-table.

Creating the function

CREATE FUNCTION functionSetOrderPrice()
RETURNS trigger AS
$$
BEGIN
-- Getting the particular part's price
part_price := (SELECT price FROM Parts WHERE Parts.ID=NEW.IDPart);

-- Multiplying the price with the quantity to get order total price
order_price := part_price * NEW.quantity;

-- Let's set the Orders.price to the correct value!
NEW.price = order_price;
return NEW;
END;
$$ LANGUAGE plpgsql;

Some things to be mindful of, and can help you and others understand your database is to stick to these principles:

  • Table-names should always be plural and capitalized: Parts, Orders, Users
  • Attribute-names should always be lower-case and singular: quantity, name, id

Also, if you were looking for triggers for MySQL, the syntax is slightly different, but the thought-process is the same. Here's a good example.



Related Topics



Leave a reply



Submit