如何在mysql存储过程中使用case-when语句?

时间:2011-03-02 13:15:11

标签: mysql timestamp procedures case-when

我想使用request_time参数自动设置session_id,所以我选择了一个包含case语句的mysql存储过程。看看。

create procedure upd_userinput(in  request_time timestamp, out user_session_id int) 

begin 

update user_input;

case request_time

when time(request_time) < '9:15:00' && time(request_time) > '8:15:00' 
then set user_session_id = 1; 

when  time(request_time)< '10:15:00' && time(request_time) > '11:15:00' 
then set user_session_id =2; 

end case; 
end
//

但是在//后输入时出现1064错误。我已经检查了mysql文档,我认为案例语法是正确的。

请帮助。

2 个答案:

答案 0 :(得分:6)

delimiter //

create procedure upd_userinput(in request_time TIMESTAMP,out time TIME, out user_session_id INT)     

begin      

set time = time(request_time);    

case  
when time < '09:15:00' && time > '08:15:00' then      
set user_session_id = 1; 

when time < '10:15:00' && time > '11:15:00' then
set user_session_id = 2;  

else set user_session_id =3;

end case;  
end //

答案 1 :(得分:1)

该案例必须至少与给定的一个语句匹配,否则您将收到此错误。为避免错误,请在其中包含其他内容。

create procedure upd_userinput(in  request_time timestamp, out user_session_id int) 
begin 
update user_input;
case request_time
when time(request_time) < '9:15:00' && time(request_time) > '8:15:00' then
set user_session_id = 1; 
when  time(request_time)< '10:15:00' && time(request_time) > '11:15:00' then
set user_session_id =2; 
else set user_session_id =0; 
end case; 
end