Cannot SELECT from UPDATE RETURNING clause in postgres

前端 未结 7 1077
旧时难觅i
旧时难觅i 2020-12-03 10:36

I isolatet the problem from a much more complex query. Here the test scenario

DROP TABLE test; 
CREATE TABLE test (
  id integer,
  description varchar(100)
         


        
7条回答
  •  盖世英雄少女心
    2020-12-03 11:39

    DROP TABLE IF EXISTS test_tab;
    
    CREATE TABLE test_tab (
      id integer,
      description varchar(100)
    );
    
    INSERT INTO test_tab(id, description) VALUES (1,'new'); 
    INSERT INTO test_tab(id, description) VALUES (2,'new'); 
    
    SELECT * from test_tab;
    
    DO $$
    DECLARE
        myID    test_tab.id%TYPE;
        testID  test_tab.id%TYPE;
        cur_IDs CURSOR for select id from test_tab;
    BEGIN
        OPEN cur_IDs;
        LOOP
            FETCH cur_IDs into testID;
            EXIT WHEN testID is NULL;
    
            UPDATE test_tab SET description='test' WHERE id = testID RETURNING id into myID;
            raise notice 'myID %', myID;
        END LOOP;
        CLOSE cur_IDs;
    END$$;
    
    
    DROP TABLE IF EXISTS test_tab;
    

提交回复
热议问题