在mysql中使用select声明和使用变量

时间:2011-12-15 13:05:10

标签: mysql stored-procedures

我有以下存储过程。它似乎不起作用。我有什么不对的吗?

当我在第4行声明角色时发生错误。

create procedure getRole(in x mediumint unsigned)
begin

DECLARE role INT DEFAULT 3
SELECT user_level INTO role  FROM login_users WHERE user_id = x

        CASE role  
            WHEN 1 THEN  

            WHEN 2 THEN  
                select
                 u.user_level As role,
                 a.id As id,
                 'advisor' As user
                from
                 login_users u
                 inner join login_levels l on u.user_level =l.id
                 inner join rp_adviser a on u.user_id = a.user_id
                where
                 u.user_id = 11;   
            ELSE  
                select
                 u.user_level As role,
                 s.id As id,
                 'student' As user
                from
                 login_users u
                 inner join login_levels l on u.user_level =l.id
                 inner join rp_student s on u.user_id = s.user_id
                where
                 u.user_id = 9;  
                END CASE;  
    end 

2 个答案:

答案 0 :(得分:1)

试试这个:

DROP PROCEDURE IF EXISTS `getRole` $$
CREATE PROCEDURE `q1a`.`getRole` (in x mediumint unsigned)
BEGIN

DECLARE role INT DEFAULT 3;
SELECT user_level INTO role  FROM login_users WHERE user_id = x;

if(role = 1 or role = 1)
then
select
                 u.user_level As role,
                 a.id As id,
                 'advisor' As user
                from
                 login_users u
                 inner join login_levels l on u.user_level =l.id
                 inner join rp_adviser a on u.user_id = a.user_id
                where
                 u.user_id = 11;
else
select
                 u.user_level As role,
                 s.id As id,
                 'student' As user
                from
                 login_users u
                 inner join login_levels l on u.user_level =l.id
                 inner join rp_student s on u.user_id = s.user_id
                where
                 u.user_id = 9;
end if;

END $$

答案 1 :(得分:0)

实际上,在查询中role语句中声明和使用变量CASE是可以的,但是您需要将存储过程中的语句与半字母;分开,就像他的:

DECLARE role INT DEFAULT 3;
SELECT user_level INTO role  FROM login_users WHERE user_id = x;

    CASE role
    ...