MySQL中的临时表定义

时间:2013-01-20 17:26:21

标签: mysql sql stored-procedures temp-tables

我有一个使用临时表的存储过程,以便我可以总结某个产品类别中所有产品的销售情况。当我尝试运行代码时失败了。我搜索谷歌和这里的stackoverflow但无法找到我做错了什么。我在Windows Server上使用MySQL服务器5.5。

CREATE PROCEDURE `getStatistics`(IN `startDate` date,IN `endDate` date,IN  `categoryName` varchar)
BEGIN
    CREATE TEMPORARY TABLE procResult(productName VARCHAR, amount INT);
    CREATE TEMPORARY TABLE tblProductID(SELECT ID, `name` FROM product WHERE categoryID = (SELECT ID FROM category WHERE `name` = categoryName));
    DECLARE done_amt, done_PID INT DEFAULT FALSE;
    DECLARE amount, productID INT DEFAULT 0;
    DECLARE pidCursor CURSOR FOR SELECT ID, `name` FROM tblProductID;
    DECLARE amtCursor CURSOR FOR SELECT orderlines.amount FROM orderlines WHERE orderlines.productID = productID;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done_amt = TRUE;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done_PID = TRUE;

    OPEN pidCursor;

    pid_loop:LOOP
        DECLARE productName VARCHAR;
        FETCH pidCursor INTO productID, productName;

        IF done_PID THEN
            LEAVE pid_LOOP;
        END IF;

        OPEN amtCursor;

        amt_loop:LOOP
            DECLARE tmpAmount INT DEFAULT 0;
            FETCH amtCursor INTO tmpAmount;

            IF done_amt THEN
                LEAVE amt_loop;
            END IF;

            amount = amount + tmpAmount;
        END LOOP;

        CLOSE amtCursor;

        IF amount > 0 THEN
            INSERT INTO procResult VALUES (productName, amount);
            amount = 0;
        END IF;
    END LOOP;

    CLOSE pidCursor;
END;

1 个答案:

答案 0 :(得分:1)

  1. 您必须定义VARCHAR类型变量的长度,例如存储过程的categoryName参数;

  2. 在任何其他命令之前,您必须在DECLARE的最开始BEGIN ... END compound statement block CREATE TABLE ... SELECT所有局部变量;

  3. indeterminately的语法不正确;

  4. 您已针对相同的SQL条件声明了两个处理程序,其中只有一个将被执行(CREATE PROCEDURE);

  5. 您需要更改客户端的语句分隔符,以便了解过程体中出现的分号不会终止{{3}}语句;

  6. 在SQL中执行相当简单的任务是一个非常复杂的过程:

    CREATE TEMPORARY TABLE procResult
      SELECT   product.name, SUM(orderlines.amount) AS amount
      FROM     orderlines
          JOIN product  ON  product.ID = orderlines.productID
          JOIN category ON category.ID = product.categoryID
      WHERE    category.name = ?
      GROUP BY product.ID
      HAVING   amount > 0