IF附近无法识别的语句-使用IF存在

时间:2019-07-26 07:27:35

标签: mysql

如果date_in和date_out都为空,我想更新表roomstatus中的行,其中room_id = @id。否则,我需要插入新行,例如room_id = @ id,date_in = @ dateIn,date_out = @dateIN

IF ((SELECT date_in FROM roomstatus WHERE room_id = @id)= NULL AND (SELECT date_out FROM roomstatus WHERE room_id = @id)= NULL ) THEN 
    UPDATE roomstatus SET date_in = @dateIN, date_out = @dateOut WHERE roomid = @id
ELSE
    INSERT INTO roomstatus (room_id,date_in,date_out) VALUES (@id,@dateIn,@dateOut)
END IF;

MySQL说:

> #1064 - 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 'IF ((SELECT date_in FROM roomstatus WHERE room_id = @id)= NULL
> AND (SELECT date_' at line 1

1 个答案:

答案 0 :(得分:0)

您的程序有些错误 1)每个语句都需要一个终止符2)MYSQL无法将列名与参数名区分开,例如WHERE room_id = roomID-(mysql会将列与其自身进行比较),您必须提供该信息3)关闭开始的结尾需要具有结束定界符。以下在语法上是正确的

DROP PROCEDURE IF EXISTS P;

DELIMITER // 
CREATE PROCEDURE P(IN INdateIn DATETIME(6) , IN INdateOut DATETIME(6), IN INroomID INT(11)) 
BEGIN 
    IF EXISTS (SELECT room_id FROM roomstatus WHERE room_id = INroomID AND date_in = NULL AND date_out = NULL ) THEN
     UPDATE roomstatus 
        SET date_in = INdateIn , date_out = INdateOut 
         WHERE room_id = INroomID ;
    ELSE 
        INSERT INTO roomstatus (room_id,date_in,date_out) VALUES (INroomID,INdateIn,INdateOut); 
    END IF;
END //
DELIMITER ; 

从功能上我不太确定,没有错误检查以确保您已设置参数来实现想要的操作。例如,您没有测试indateout,因此代码可能会输入将indateout设置为null并将indatein设置为有效值的更新逻辑-下次调用该过程时,您可能会输入插入逻辑并可能以重复项结尾。 / p>