MYSQL stored procedure, case

2019-08-24 02:10发布

I've consulted this page: http://dev.mysql.com/doc/refman/5.1/en/case.html as well as this one, but can't get a simple procedure to work....


UPDATE: To clearify what I want to do: I want to select all rows from a table where the field id is either 1, 0 or could be either of them. This is specified by an input parameter to the procedure, which takes values 0,1 or 2.

So if _id = 0 I want: select * from TABLE where id = 0

If _id = 1 I want: select * from TABLE where id = 1

And if _id = 2 I want: select * from TABLE where id in (0,1)

I was hoping I could get the rest of it to work by myself if I only got the simple case-statement below to work...


What I want to do is something like:

begin
    select * from TABLE where
        case _id
        when  0 then id=0
        else id = 1
        end as id
end

which gives error "You have an error in your SQL syntax".

I've also tried:

begin
    select * from TABLE where
        case _id
        when  0 then id=0
        else id=1
        end case
end

which gives the same error. Obviously I've got the wrong syntax somewhere, but I can't figure out where... Can anyone help me out?

Thanks, Niklas

2条回答
在下西门庆
2楼-- · 2019-08-24 02:28

build the query to look like this... mySQL case have a different syntax from C and Java...

set @input=2;

select * from foo 
 where 
     case when @input =2 then  value in ( 1, 0)  else
       value =  @input end;

live demo with sql fidle

查看更多
来,给爷笑一个
3楼-- · 2019-08-24 02:38

Try this:

begin
    select *,
        case _id
        when 0 then 0
        else 1
        end as id
    from table
end

When used as part of a SELECT query, WHEN is not a statement, it's a control flow function.

You can also express this as:

begin
    select *, _id != 0 as id
    from table
end
查看更多
登录 后发表回答