MySQL How to INSERT INTO [temp table] FROM [Stored Procedure]

前端 未结 5 1130
心在旅途
心在旅途 2020-12-03 13:32

This is very similar to question 653714, but for MySQL instead of SQL Server.

Basically, I have a complicated select that is the basis for several stored procedures.

5条回答
  •  误落风尘
    2020-12-03 14:22

    i know this is coming really late but since it took me ages to find a real solution i might as well share. I worked on an example that is below.

    the tables created are:

    CREATE TABLE BOOK(
    B_ID INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(B_ID),
    TITLE VARCHAR(100),
    DESCRIPTION VARCHAR(30),
    PRICE DOUBLE);
    
    CREATE TABLE BOOK_COMMENT(
    
    PRIMARY KEY(B_C_ID),
    B_C_ID INT NOT NULL AUTO_INCREMENT,
    REMARK VARCHAR(120),
    B_ID INT,
    FOREIGN KEY(B_ID) REFERENCES BOOK(B_ID));
    
    CREATE TABLE AUTHOR(
    A_ID INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(A_ID),
    A_NAME CHAR(15),
    B_ID INT,
    
    FOREIGN KEY(B_ID) REFERENCES BOOK(B_ID));
    
    1. DELIMITER
    
    CREATE PROCEDURE BOOK_IMPORTANT( _PRICE DOUBLE, _B_ID INT, A_NAME CHAR(15), _BD_ID INT)
    
    BEGIN
    
    INSERT INTO BOOK(PRICE)
    
    VALUES(_PRICE);
    
    SET _B_ID=LAST_INSERT_ID();
    
    INSERT INTO BOOK_COMMENT(B_ID)
    
    VALUES(_B_ID);
    
    SET _BD_ID=LAST_INSERT_ID();
    
    INSERT INTO AUTHOR(A_NAME,B_ID)
    
    VALUES(A_NAME,_BD_ID);
    
    END
    

    then use the following to insert the values.

    CALL BOOK_IMPORTANT('0.79',LAST_INSERT_ID(),'',LAST_INSERT_ID());
    

    LAST_INSERT_ID() takes the last auto increment of the table and inserts it into the referencing column of the child table.

    In the procedure parameters _B_ID and _BD_ID represent the B_ID since I need B_ID as a foreign key in both tables.

    Sorry for the excess wording. All the other guys expect you to automatically know how to do it. Hope it helps

提交回复
热议问题