代码之家  ›  专栏  ›  技术社区  ›  Konstantin Chsherbakov

带变量值的pl pgsql移动

  •  2
  • Konstantin Chsherbakov  · 技术社区  · 6 年前

    我有以下使用光标实现分页的功能。函数接受参数 i_limit i_offset .

    begin
      -- Search resources.
      select into found_keys trgm_search_resources(i_search_query);
      -- Open cursor
      open master_event_curs(found_keys);
      -- Reposition cursor if the @i_offset is specified
      -- TODO: Replace 5 with variable
      move forward i_offset in master_event_curs;
    
      -- Limit number of retrieved items
      loop
        exit when i >= i_limit;
        -- Fetch data to the record
        fetch master_event_curs into recordvar;
        exit when not found;
        i = i + 1;
    
        -- Return master event info.
        return next (select get_master_event_info(recordvar."master_event_uid" :: bigint, i_return_langs));
      end loop;
      -- Return info of found master events.
      return;
    end;
    

    当我使用 move forward 5 in master_event_curs 一切正常,但当我试图用动态替换5时 I_偏移 变量,SQL显示语法错误 {char} unexpected .

    我尝试使用显式强制转换,使用 execute 声明,但不起作用。

    有人能告诉我怎么做吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   klin    6 年前

    execute format()

    execute format('move forward %s in master_event_curs', i_offset);
    
        2
  •  2
  •   Pavel Stehule    6 年前

    do $$
      declare s cursor for select * from pg_class;
      r record;
      i_offset int default 5; 
    begin
      open s;
      move forward i_offset in s;
      fetch s into r;
      raise notice '%', r;
      close s;
    end;
    $$;
    
    NOTICE: (pg_toast_2609,99,11585,0,10,0,2834,0,0,0,0,0,t,f,p,t,3,0,f,f,f,f,f,f,t,n,f,0,561,1,,,)
    

    也许你用的是太老的PostgreSQL版本,或者有什么不同的问题,但是 MOVE FETCH 命令支持表达式,因此不需要使用动态SQL。