IF within SELECT

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • carmelo

    IF within SELECT

    Hello,
    I'm working on a DB on which I can run only SELECT commands, so I'd
    like to modify these UPDATE commands, into one SELECT command, which
    makes use of IF statements:

    update Table
    set field1=field2

    update Table
    set field1=field3
    where 'condition'

    I've modified it into this:
    select *,
    IF(condition,fi eld3,field2)
    END IF as newField
    from Table

    I tried this way too:
    select *,
    IF(condition) THEN field3
    ELSE field2
    END IF as newField
    from Table


    It doesn't work... I hope you can help me
    Thank you very much in advance
    Carmelo
  • Plamen Ratchev

    #2
    Re: IF within SELECT

    IF is a control of flow statement and you cannot use it like that in the
    query. You can use the CASE function:

    SELECT CASE WHEN condition
    THEN col3
    ELSE col2
    END AS new_col
    FROM Table;

    HTH,

    Plamen Ratchev


    Comment

    • carmelo

      #3
      Re: IF within SELECT

      On 10 Giu, 00:28, "Plamen Ratchev" <Pla...@SQLStud io.comwrote:
      IF is a control of flow statement and you cannot use it like that in the
      query. You can use the CASE function:
      >
      SELECT CASE WHEN condition
                        THEN col3
                        ELSE col2
                END AS new_col
      FROM Table;
      >
      HTH,
      >
      Plamen Ratchevhttp://www.SQLStudio.c om
      OK thanks. I'm using successfully the CASE function

      Comment

      Working...