MySQL存储例程错误

时间:2018-02-27 14:14:58

标签: mysql loops stored-procedures while-loop do-while

我现在正在MySQL中创建Stored Routine,我在查询时遇到了这个错误。

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your SQL server version for the right syntax to use near 'DATE_ADD(sDate, INTERVAL 1 DAY); END WHILE; END IF; END' at line 30

这是我的查询:

BEGIN
DECLARE code CHAR (5) DEFAULT (00000);
IF (SELECT COUNT(allocationDate) FROM ROOM_ALLOCATION WHERE allocationDate 
 BETWEEN startDate AND (SELECT DATE_SUB(endDate,INTERVAL 1 DAY)) > 0) THEN    
    WHILE DATEDIFF(sDate, eDate) <> 0 DO
        SET code = 0;
        WHILE code = 0 DO
            SET code =(SELECT LEFT(MD5(RAND()*100), 5));
            IF exists (SELECT * FROM BOOKING_DETAIL WHERE bDetailCode LIKE code)
            THEN 
                SET code = 0;
        END IF;
        END WHILE;
        INSERT INTO ROOM_ALLOCATION (rAllocationCode, roomID, bDetailID, allocationDate)
        VALUES
        (rAlloCode, roIDm, bDetID, sDate);
        DATE_ADD(sDate, INTERVAL 1 DAY);
    END WHILE;
END IF;
END

我绝望在哪里弄错了这个查询?

事先谢谢你。

此致

1 个答案:

答案 0 :(得分:1)

sDate需要声明为变量,我假设您将startDate传递给过程。

您将sDate设置为startDate,现在允许您使用DATEADD操作sDate。 DATEADD返回值,它不修改变量;所以你使用SET并将DATEADD的返回值赋值给sDate,这样你的WHILE循环就会在下一个循环中使用它。

因为eDate不存在,我修改了eDate的实例以使用endDate我假设你也传入了。因为您没有修改该值,所以将它重新分配给另一个变量是没有意义的。

BEGIN
DECLARE code CHAR (5) DEFAULT (00000);
DECLARE sDate DATETIME = startDate;
IF (SELECT COUNT(allocationDate) FROM ROOM_ALLOCATION WHERE allocationDate 
 BETWEEN startDate AND (SELECT DATE_SUB(endDate,INTERVAL 1 DAY)) > 0) THEN    
    WHILE DATEDIFF(sDate, endDate) <> 0 DO
        SET code = 0;
        WHILE code = 0 DO
            SET code =(SELECT LEFT(MD5(RAND()*100), 5));
            IF exists (SELECT * FROM BOOKING_DETAIL WHERE bDetailCode LIKE code)
            THEN 
                SET code = 0;
        END IF;
        END WHILE;
        INSERT INTO ROOM_ALLOCATION (rAllocationCode, roomID, bDetailID, allocationDate)
        VALUES
        (rAlloCode, roIDm, bDetID, sDate);
        SET sDate = DATE_ADD(sDate, INTERVAL 1 DAY);
    END WHILE;
END IF;
END