简体   繁体   中英

Create Temporary Table in a Stored Procedure Including "WITH" [MySQL]

I have a stored procedure written in MySQL, and I want to store its results in a temporary table. Here is the code:

DELIMITER $$
CREATE PROCEDURE GetRequiredItemsCount(
    IN item VARCHAR(16),
    IN parent_item_count INT)

    BEGIN
/*      DROP TABLE IF EXISTS required_items;
        CREATE TEMPORARY TABLE required_items AS */
        
            WITH RECURSIVE bom_temp AS (

                SELECT bom.item_id, bom.component_id, bom.bom_multiplier
                FROM bom
                WHERE bom.item_id = item
                
                UNION ALL

                SELECT child.item_id, child.component_id, child.bom_multiplier
                FROM bom_temp parent
                    JOIN bom child ON parent.component_id = child.item_id
                )

            SELECT DISTINCT component_id, SUM(bom_multiplier)*parent_item_count
            FROM bom_temp
            GROUP BY component_id;
    END$$
DELIMITER;

It is currently working, but when I remove the comments from the part CREATE TEMPORARY TABLE required_items AS , it raises error.

I think the problem is the use of WITH , but I could not find any similar cases on the.net.

I would appreciate your suggestions and comments, thanks!

PS: "bom" table is generated as follows:

CREATE TABLE bom (  item_id VARCHAR(16),
                    component_id VARCHAR(16),
                    bom_multiplier INT NOT NULL,
                    PRIMARY KEY (item_id, component_id));

INSERT INTO bom (item_id, component_id, bom_multiplier)
VALUES  ("001", "002", 1),
        ("001", "003", 1),
        ("002", "004", 3),
        ("002", "005", 3); 

The error message was pointing out the incorrect column name for SELECT DISTINCT component_id, SUM(bom_multiplier)*parent_item_count . The problem was solved when I appended AS required_amount to that line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM