1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Create a trigger

Discussion in 'Databases' started by siddharth007, Nov 18, 2013.

  1. #1
    Hi all.I am required to create a trigger on an existing table (say x) wherein we have attribute called as level (with accepted values as low,medium and high). Whenever a record is inserted into an existing table (x) with 'level' as 'high',the entire record should be copied to the new table (say y). Is this possible to accomplish using triggers ?
     
    siddharth007, Nov 18, 2013 IP
  2. Bec0de

    Bec0de Well-Known Member

    Messages:
    46
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    115
    #2
    Yes, the trigger would be similar to this (I suppose you're using MySQL):
    DELIMITER $$
    
    CREATE TRIGGER copy_high_record
    BEFORE INSERT ON X
    FOR EACH ROW BEGIN
      IF (NEW.level = 'high') THEN
        // your queries
      END IF;
    END$$
    
    DELIMITER ;
    Code (markup):
     
    Bec0de, Nov 18, 2013 IP
  3. siddharth007

    siddharth007 Greenhorn

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    here NEW is the alias for the existing table right? So my query would be something like this
    insert into Y (column1,column2) values (NEW.description,NEW.level);
    Code (markup):
    Am i right?
     
    siddharth007, Nov 18, 2013 IP
  4. Bec0de

    Bec0de Well-Known Member

    Messages:
    46
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    115
    #4
    Exactly :) NEW references to the newly inserted row.
     
    Bec0de, Nov 19, 2013 IP
  5. siddharth007

    siddharth007 Greenhorn

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #5
    DELIMITER $$


    CREATE TRIGGER copy_low_record
    AFTER INSERT ON ossec.data
    FOR EACH ROW BEGIN
    DECLARE X varchar(10);
    SET X=(select level from ossec.alert_levels where rule_id in(select rule_id from ossec.alert where id in (select max(id) from ossec.alert)));
    IF (X='Low') THEN
    Insert into ossec.data_critical (server_id,user,full_log,timestamp) values (NEW.server_id,NEW.user,NEW.full_log,NEW.timestamp);
    END IF;
    END$$

    DELIMITER ;

    Please help me with this.I am required to insert the value in the 'data_critical' table if the output of the previous query (stored in variable X) is Low.
     
    siddharth007, Dec 3, 2013 IP