MySQL Trigger - Storing a SELECT in a variable

后端 未结 6 1312
孤独总比滥情好
孤独总比滥情好 2020-12-02 22:16

I have a trigger in which I want to have a variable that holds an INT I get from a SELECT, so I can use it in two IF statements instead of calling the SEL

6条回答
  •  情歌与酒
    2020-12-02 22:29

    I'm posting this solution because I had a hard time finding what I needed. This post got me close enough (+1 for that thank you), and here is the final solution for rearranging column data before insert if the data matches a test.

    Note: this is from a legacy project I inherited where:

    1. The Unique Key is a composite of rridprefix + rrid
    2. Before I took over there was no constraint preventing duplicate unique keys
    3. We needed to combine two tables (one full of duplicates) into the main table which now has the constraint on the composite key (so merging fails because the gaining table won't allow the duplicates from the unclean table)
    4. on duplicate key is less than ideal because the columns are too numerous and may change

    Anyway, here is the trigger that puts any duplicate keys into a legacy column while allowing us to store the legacy, bad data (and not trigger the gaining tables composite, unique key).

    BEGIN
      -- prevent duplicate composite keys when merging in archive to main
      SET @EXIST_COMPOSITE_KEY = (SELECT count(*) FROM patientrecords where rridprefix = NEW.rridprefix and rrid = NEW.rrid);
    
      -- if the composite key to be introduced during merge exists, rearrange the data for insert
      IF @EXIST_COMPOSITE_KEY > 0
      THEN
    
        -- set the incoming column data this way (if composite key exists)
    
        -- the legacy duplicate rrid field will help us keep the bad data
        SET NEW.legacyduperrid = NEW.rrid;
    
        -- allow the following block to set the new rrid appropriately
        SET NEW.rrid = null;
    
      END IF;
    
      -- legacy code tried set the rrid (race condition), now the db does it
      SET NEW.rrid = (
        SELECT if(NEW.rrid is null and NEW.legacyduperrid is null, IFNULL(MAX(rrid), 0) + 1, NEW.rrid)
        FROM patientrecords
        WHERE rridprefix  = NEW.rridprefix
      );
    END
    

提交回复
热议问题