Question

After hours of googling and search here , I am able to create this trigger; This trigger works well, and keeps the two tables synced in 2 different tables. (I am not worried about batched operations, that wouldn't happen). The only issue is that If the USER_ID is modified (that is primary key), it does not gets updated in 2nd table); I am not able to get the 'UPDATE' part right. What am I doing wrong?

ALTER TRIGGER [u].[SyncUsers] 
   ON  [u].[USERS] 
   AFTER INSERT,DELETE,UPDATE
AS 

BEGIN

    IF (@@rowcount = 0) RETURN;
    SET NOCOUNT ON;

    -- deleted data
    IF NOT EXISTS (SELECT * FROM inserted) 
        BEGIN
            DELETE FROM ERP_DB.u.USERS WHERE USER_ID = 
            (SELECT USER_ID FROM deleted);
            RETURN;
        END
    ELSE 
        BEGIN

            -- inserted data
            IF NOT EXISTS (SELECT * FROM deleted)
                BEGIN           
                    INSERT INTO ERP_DB.u.USERS(USER_ID, USER_NAME , DISPLAY_NAME , EMP_ID , DEPARTMENT_ID)  SELECT USER_ID, USER_NAME , DISPLAY_NAME , EMP_ID , DEPARTMENT_ID FROM inserted;
                    RETURN;
                END

            -- updated data
            ELSE
                BEGIN
                    UPDATE UU
                        SET UU.USER_ID = i.USER_ID,
                            UU.USER_NAME = i.USER_NAME ,
                            UU.DISPLAY_NAME = i.DISPLAY_NAME ,
                            UU.DEPARTMENT_ID = i.DEPARTMENT_ID ,
                            UU.EMP_ID = i.EMP_ID 

                            FROM ERP_DB.u.USERS AS UU
                INNER JOIN Inserted AS i ON UU.USER_ID = i.USER_ID

            RETURN;
        END 
    END -- updated data
    END
END
Was it helpful?

Solution

Of course it doesn't, because the PK of the table was changed. The value of user_id column in inserted pseudotable is different from the one in the UU table. You need the value from deleted table to match the user_id column, and everything else from inserted. But the problem is that there is no way to match inserted and deleted tables any more, when the PK was changed. A mess.

If it's always a single-row update, you might get away with it, using a cross join between UU and inserted and a `WHERE UU.user_id = (SELECT user_id from deleted)' in the update statement.

Mutch better -- disallow the PK update altogether. After all, it's not the same row any more if the PK's changed.

OTHER TIPS

You should never be modifying Primary Key.

If it is some thing that can be modified , it can not be a primary key.

Primary key should generally be Auto Generated and must be read only.

So, what you are assuming might happen is wrong or either your database design is wrong.

If primary key is editable, you can not ensure uniqueness which violates prime quality of Primary Key

Hope this helps..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top