开发者

Creating a function in mysql

I would like to create a function or procedure that I can use in mysql but I'm not sure what the sy开发者_开发知识库ntax would be. What I want to do is take the value from a column and see if it's a 1 or 2, and based on that, return the value from either column A or B. So for example, my select function would be something like:

select a, b, c, functionA(c) from table;

Below is the pseudo-code of my function

functionA(int x){
      if(x==1)
          //return value in column A
      else
          //return value in column B
}


select a, b, c, IF(c=1, a, b) from table;

or you can use select case but I think IF is more readable.

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html


A function won't be able to return anything from the table that you don't pass in. To do what you want requires 3 parameters:

create function functionA(p1 integer, p2 integer, p3 integer) returns integer
begin
    if p1 = 1 then
        return p2
    else
        return p3
    end if;
end;

..and your query would be:

select a, b, c, functionA(c, a, b) from table;

However it's more efficient and easier to just case or if for such a simple query:

select case when c=1 then a else b end from table;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜