0
votes

I need to create a after insert trigger in mysql.

I have 3 tables like this.

Table1

ProjectID(TestP), Site(st1,st2,st3)

Table2

ProjectName,ProjectID,ProjectDetails

Table3

ProjectName,ProjectDetails,Site

Now I have to write a trigger which will insert 3 row in Table3, when I am inserting 1 row in Table2 (TestProject,TestP,Details1)

The value should be like this in Table3

Row1 : TestProject,Details1,st1 Row2 : TestProject,Details1,st2 Row3 : TestProject,Details1,st3

Please somebody help me.

1

1 Answers

0
votes

First add this procedure to your database

http://forge.mysql.com/tools/tool.php?id=4 (edit 2020-09-09, link is now dead but wayback machine found the source)

DELIMITER //
 
DROP PROCEDURE IF EXISTS split_string //
CREATE PROCEDURE split_string (
    IN input TEXT
    , IN `delimiter` VARCHAR(10) 
) 
SQL SECURITY INVOKER
COMMENT 
'Splits a supplied string using using the given delimiter, 
placing values in a temporary table'
BEGIN
    DECLARE cur_position INT DEFAULT 1 ;
    DECLARE remainder TEXT;
    DECLARE cur_string VARCHAR(1000);
    DECLARE delimiter_length TINYINT UNSIGNED;
 
    DROP TEMPORARY TABLE IF EXISTS SplitValues;
    CREATE TEMPORARY TABLE SplitValues (
        value VARCHAR(1000) NOT NULL PRIMARY KEY
    ) ENGINE=MyISAM;
 
    SET remainder = input;
    SET delimiter_length = CHAR_LENGTH(delimiter);
 
    WHILE CHAR_LENGTH(remainder) > 0 AND cur_position > 0 DO
        SET cur_position = INSTR(remainder, `delimiter`);
        IF cur_position = 0 THEN
            SET cur_string = remainder;
        ELSE
            SET cur_string = LEFT(remainder, cur_position - 1);
        END IF;
        IF TRIM(cur_string) != '' THEN
            INSERT INTO SplitValues VALUES (cur_string);
        END IF;
        SET remainder = SUBSTRING(remainder, cur_position + delimiter_length);
    END WHILE;
 
END //

It will split any string into rows in a temporary table.

Send the column from Table1 into that procedure and use the resulting temporary table to insert values into Table3