开发者

How to use a case-when statement in a mysql stored procedure?

I want to set the session_id automatically using the request_time parameter so i opted for a mysql stored procedure that contains a case statement.Here goes.

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
//

However i get a 1064 error on enter afte开发者_如何学运维r //. I have checked the mysql documentation i think the case syntax is correct.

Help please.


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 //


the case must match at least one of the given statements, otherwise you will get this error. To avoid the error include an else in it.

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


The best way To use a case-when statement in a mysql stored procedure is:

DELIMITER $
CREATE PROCEDURE my_pro()
BEGIN
UPDATE users 
SET phone = 
(
    CASE 
        WHEN substr(phone, 2,1) = '3' THEN concat('04', substr(phone, 2))
        WHEN substr(phone, 2,1) = '2' THEN concat('05', substr(phone, 2))
    END
);
END $
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜