Error when setting n_distinct using a plpgsql variable

后端 未结 1 1249
有刺的猬
有刺的猬 2020-12-04 03:16

I tried to use a function to set the n_distinct value for a table. The code is as follows:

create temporary table _temp
(
  id integer
);

create function pg         


        
相关标签:
1条回答
  • 2020-12-04 03:52

    This is by design. The explanation can be found in the chapter Variable Substitution:

    Variable substitution currently works only in SELECT, INSERT, UPDATE, and DELETE commands, because the main SQL engine allows query parameters only in these commands. To use a non-constant name or value in other statement types (generically called utility statements), you must construct the utility statement as a string and EXECUTE it.

    You cannot parameterize the value in a dynamic statement with EXECUTE either because, quoting the chapter Executing Dynamic Commands:

    Another restriction on parameter symbols is that they only work in SELECT, INSERT, UPDATE, and DELETE commands. In other statement types (generically called utility statements), you must insert values textually even if they are just data values.

    The only option in a plpgsql function is to concatenate the value into the command string. You might use format(), but for the simple example, plain concatenation is safe and easy::

    CREATE OR REPLACE FUNCTION pg_temp.setdistinct(_cnt real)
      RETURNS void AS
    $$
    BEGIN
       EXECUTE 'ALTER TABLE _temp ALTER COLUMN id SET (n_distinct=' || _cnt || ')';
    END
    $$ LANGUAGE plpgsql;
    

    Using an undocumented "temporary" function for the demo like in the question.
    BTW, about n_distinct.

    0 讨论(0)
提交回复
热议问题