存储过程sql语法错误

时间:2013-06-05 10:35:51

标签: mysql

我在数据库中有5个表

ApartamentClass(idclass,descript)
Room(idroom,idclass,beds,isfree)
ItemPrice(iditem,idclass,description,price)
Client(idclient,fio)
Active(idcontract,idclient,idroom,days,price,idclass)

我需要创建一个存储过程,检查是否存在具有某个班级(param1)的免费房间和床位数(param2),并为此房间和客户创建租房合同(fio)(param3)好几天(param4)。 价格取决于房间的等级(较高的等级 - >一张床和一天的较高价格)。

create procedure UserRequest(
    in param1 int,
    in param2 int,
    in param3 varchar(100),
    in param4 int
)
begin   
    declare iroom int default 0;
    select idroom into iroom from room
    where beds = param2 and idclass = param1 and isfree = 0
    limit 1;


    if not (iroom=0) then
        update room set isfree = 1
        where idroom = iroom;
    end if;


    declare iclient int default 0;
    select idclient into iclient from client
    where fio = param3
    limit 1;


    declare bedprice decimal default 0.0;
    select (param2 * price) into bedprice from itemprice
    where description = "bed" and idclass = param1;

    declare dayprice decimal default 0.0;
    select (param4 * price) into dayprice from itemprice
    where description = "day" and idclass = param1;

    declare price decimal default 0.0;
    set price = bedprice + dayprice;


    insert into active(idclient,idroom,days,price,idclass)
    values(iclient,iroom,param4,price,param1);
end

但我总是得到SQL语法错误。我无法解决问题所在。 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'declare iclient int default 0; select idclient into iclient from client wh' at line 20

1 个答案:

答案 0 :(得分:1)

所有DECLARE语句必须位于BEGIN ... END块的开头,如MySQL文档中所述: http://dev.mysql.com/doc/refman/5.0/en/declare.html

  

DECLARE只允许在BEGIN ... END复合语句中使用,并且必须在任何其他语句之前的开头。

因此,您可能需要尝试以下代码:

create procedure UserRequest(
    in param1 int,
    in param2 int,
    in param3 varchar(100),
    in param4 int
)
begin   
    declare iroom int default 0;
    declare iclient int default 0;
    declare bedprice decimal default 0.0;
    declare dayprice decimal default 0.0;
    declare price decimal default 0.0;

    select idroom into iroom from room
    where beds = param2 and idclass = param1 and isfree = 0
    limit 1;


    if not (iroom=0) then
        update room set isfree = 1
        where idroom = iroom;
    end if;


    select idclient into iclient from client
    where fio = param3
    limit 1;

    select (param2 * price) into bedprice from itemprice
    where description = "bed" and idclass = param1;

    select (param4 * price) into dayprice from itemprice
    where description = "day" and idclass = param1;

    set price = bedprice + dayprice;


    insert into active(idclient,idroom,days,price,idclass)
    values(iclient,iroom,param4,price,param1);
end