简体   繁体   中英

INSERT trigger to update a field that is NOT NULL in the same table

I have a situation where I need to merge two product tables into one and need to keep both id fields. The Id field is the pk and an identity column. On insert I want to update the prodId to match the Id of the newly inserted row. This is what I have but I get an error saying that I cannot insert null into ProductId. What am I doing wrong?

ALTER TRIGGER SyncId
    ON Product
FOR INSERT
AS
BEGIN
    DECLARE @ID INT
    SET @ID = (SELECT ID FROM Inserted)
    UPDATE Product SET
        ProdId = @ID
    WHERE
        Id = @ID    
END

You could create an INSTEAD OF trigger for the INSERT . You would then have to recreate the actual INSERT logic. You might need a view of the table for the trigger to sit on though... I don't recall if an INSERT within the trigger will work or not and can't test it right now.

Also, your trigger as written will only work if a single row is being updated. You should always write your triggers to be able to handle multiple rows in the INSERTED and DELETED tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM