0

我在数据库中有 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

4

1 回答 1

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
于 2013-06-05T11:14:46.263 回答