简体   繁体   中英

Postgres CASE Statement in an insert

I have a table that i had to ALTER in Postgres. I would now like to insert some values for the rows that exists in the table based on a condition. I'm looking at using CASE blocks!

Here is what I have:

INSERT INTO MyTable (value1, value2) values
    (1, SELECT t.name,
          CASE WHEN t.name IN ('MyName') THEN 1
          ELSE 2
        END AS value2
       FROM MyTable t);

I get an error:

ERROR: syntax error at or near "select"
SQL state: 42601
Character: 71

Any clues what it is?

OK, this is the insert query with the syntax fixed

 INSERT INTO MyTable (value1, value2) 
        SELECT t.name,
              CASE WHEN t.name IN ('MyName') THEN 1
              ELSE 2
            END AS value2
           FROM MyTable;

If you're trying to change existing rows, you need an update query, eg

-- first update, set value1 to 1 and value2 for all rows
UPDATE MyTable set value1 = 1,value2 = 2;

-- next query. Set value2 = 1 for only those rows matching your criteria
 UPDATE MyTable
    SET value2 = 1 WHERE name IN ('MyName');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM