2013-06-05 87 views
0

我有在數據庫表5個存儲過程的SQL語法錯誤

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

所有聲明語句必須在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 
+0

是它的工作原理!但爲什麼'declare'的位置在MySQL中確實存在? – lapots