PDA

View Full Version : Is it possible to put IF/ELSE in SELECT query


hotwheelharry
08-12-2009, 09:50 AM
I need to select the values in Column B or C depending on if the value of Column A is 1 or 0.
So A determines if I add B to my results or C to my results.

Pseudo Code:

/*for each row*/
If A=1
{
insert into @results (FieldX) values (B)
}
Else
{
insert into @results (FieldX) values (C)
}


How can I do this.
Any advice is useful to this SQL noob =D

Fumigator
08-12-2009, 04:45 PM
The CASE operator is more common (and more useful) than the IF operator, but either one may be helpful to you.

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

Old Pedant
08-13-2009, 03:07 AM
Ummm...not sure this makes sense.

WHERE does column A exist? Ditto for columns B and C???

Are they in some *OTHER* table???

You can't have an INSERT into a row that depends upon the row being inserted! It isn't there yet, so how can anything depend on it???

If you meant:

INSERT INTO table1 ( FieldX )
SELECT IF( A=1, B, C ) FROM table2

*then* it makes some kind of sense.