存储过程中的sql if语句

时间:2013-12-18 14:55:32

标签: mysql sql stored-procedures

由于某些原因,MYSQL不会让我创建这个程序,有人能看出问题所在吗?

如果我删除了IF语句,但是对我来说if语句看起来没问题。

delimiter $$
create procedure add_new_room(IN buildingID INT,
              IN inName TEXT,
                              IN inWeeks INT,
                              IN inAnnual TEXT,
                              IN inWeekly TEXT)
BEGIN
DECLARE roomnameid INT;
DECLARE roomcount INT;

SELECT count(roomID) from tblRooms WHERE roomName = inName into roomcount;

if roomcount = 1 then

    SELECT roomID from tblRooms 
       WHERE roomName = inName into roomnameid;

    INSERT INTO tblAccommRoom 
      (roomWeeks,roomID,accommodationID,roomWeeklyRent, roomAnnualRent) 
    VALUES (inWeeks,roomnameid,buildingID,inWeekly, inAnnual);

else

    INSERT INTO tblRooms (roomName) VALUES inName;

    INSERT INTO tblAccommRoom 
     (roomWeeks, roomID, accommodationID, roomWeeklyRent, roomAnnualRent) 
    VALUES (inWeeks,LAST_INSERT_ID(),buildingID,inWeekly, inAnnual);

end if;

END

2 个答案:

答案 0 :(得分:0)

我会使用CASE WHEN语句而不是IF语句,这使得代码可以更加普遍地使用MS SQL和MySQL。

CASE WHEN roomcount = 1 THEN...ELSE...END

我没有对MySQL做过很多工作,但我通常也会看到括号和逗号中包含的IF语句,而不是拼写THENELSE

IF(condition,then statement,else statement)

答案 1 :(得分:0)

尝试将SELECT更改为:

SELECT count(roomID) into roomcount from tblRooms WHERE roomName = inName;

然后,你应该可以在以后使用'roomcount'。