Change more than one value in the same column with an UPDATE

Asked

Viewed 162 times

2

I have the following doubt..

I have the example table - reply in the following format

*------------*--------------*
|resposta_id | INT          |  
|pergunta_id | INT          |   
|resposta    | VARCHAR(45)  |
*------------*--------------*

With the following records:

resposta_id  pergunta_id   resposta
    1             1          ww
    2             1          ww
    3             2          xx
    4             2          xx
    5             3          xx
    6             3          xx
    7             3          xx

I’m looking to make a UPDATE to change the field of reply according to the value in the field question_id.

I tried so:

UPDATE sch_Pessoal.resposta 
    set resposta = CASE resposta 
        WHEN pergunta_id = 1 THEN 'aaa'
        WHEN pergunta_id = 2 THEN 'bbb'
        WHEN pergunta_id = 3 THEN 'ccc'
    END

But the result is this;

resposta_id  pergunta_id   resposta
    1             1          bbb
    2             1          bbb
    3             2          aaa
    4             2          aaa
    5             3          aaa
    6             3          aaa
    7             3          aaa

Someone can help?

SQL Fiddle of the structure:

Sql Fiddle

  • Only one question. It wouldn’t be "WHEN answer_id" instead of "WHEN question_id"

  • No Fabricio, in this case I wanted to modify the answer field, based on the field 'question_id' same

1 answer

2


It was just a small mistake in the syntax of CASE.

The right thing would be:

UPDATE RESPOSTA 
    SET resposta = CASE  
            WHEN pergunta_id = 1 THEN 'aaa'
            WHEN pergunta_id = 2 THEN 'bbb'
            WHEN pergunta_id = 3 THEN 'ccc'
        END

This is working the way you want, see in SQL Fiddle

This seems to have been a side effect by SGBD having understood The resposta between the CASE and the WHEN as an expression.

  • 1

    Excellent Diego, fails my same rs. Thank you so much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.