Postgres CASE声明在插页中

时间:2015-07-01 10:13:04

标签: postgresql

我有一张桌子,我不得不在Postgres中使用ALTER。我现在想根据条件为表中存在的行插入一些值。我正在考虑使用CASE块!

这就是我所拥有的:

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);

我收到错误:

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

有什么线索?

1 个答案:

答案 0 :(得分:5)

好的,这是插入查询,语法已修复

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

如果您尝试更改现有行,则需要更新查询,例如

-- 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');