开发者

SQL Trigger to update another table

I have a Maximo database that has a table structure I cannot change. I am looking to copy the primary email address into the PERSON table anytime it is created or updated. The following structure describes the PERSON table and EMAIL table


PERSON table:

PERSONID | EMAIL | ...(other irrelevant columns)...

EMAIL table:

PERSONID | EMAILADDRESS | ISPRIMARY | ...(other irrelevant columns)...

As you can see, the two tables are linked on the PERSONID column. Here is what I would like the trigger to do:

If the EMAIL table is updated or a new row is inserted, I would like to copy the EMAILADDRESS field to the corresponding entry (as linked by PERSONID) on the PERSON table IF the ISPRIMARY field is equal to 1 (1 means primary, 0 means secondary).

I have not written many triggers so I want to make sure I am only looking at the rows that are being updated or inserted into the EMAIL table and only updating the PERSON table if there is a new/updated primary email address. Thanks in advance for all of your help!


UPDATE 1:

After looking at Cade's response, here is the trigger I am beginning to form:

CREATE TRIGGER EMAIL_update ON UPDATE,INSERT  AS  BEGIN      
UPDATE p  
SET p.email = i.emailaddress
FROM dbo.PERSON as 开发者_JAVA百科p
INNER JOIN inserted AS i ON i.PERSONID = p.PERSONID AND i.isprimary=1 
END  

I believe that trigger should work anytime something is updated OR inserted to the email table.


Problem is going to be related to the lack of a primary key on the EMAIL table. Triggers work best with immutable primary keys.

Also, what if a row changes to not be primary, do you remove the entry from PERSON?

So still seems like some open questions in the problem domain, but here's a stab at what the trigger would look like. You could add some things which look for rows where a change is actually occurring - but be careful about NULLs.

CREATE TRIGGER EMAIL_update ON UPDATE
AS
BEGIN
    UPDATE PERSON
    SET EMAIL = i.EMAILADDRESS    
    FROM PERSON
    INNER JOIN inserted AS i
        ON i.PERSONID = PERSON.PERSONID
    INNER JOIN deleted AS d -- could try changing this to a left join and use same trigger for INSERT
        ON -- what? could use PERSONID, but it's not unique
    WHERE i.ISPRIMARY = 1 -- This helps with uniqueness, but what about things leaving primary?
    -- AND i.EMAILADDRESS <> PERSON.EMAIL -- Could add this (what about NULLs?)
END
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜