0

I would like to create a function or procedure that I can use in mysql but I'm not sure what the syntax 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
}
3
  • you can do this without using a function and it will perform better. select case when c=1 then a else b end from table Commented Jul 9, 2011 at 2:46
  • @Gordy - this should be posted as an answer below. Commented Jul 9, 2011 at 2:47
  • @oipsl: it is a time to remove SQL and mysql from known array in your profile )) Commented Jul 9, 2011 at 2:55

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.