代码之家  ›  专栏  ›  技术社区  ›  dland

在Postgresql中将一列的注释设置为另一列的注释

  •  6
  • dland  · 技术社区  · 17 年前

    假设我在Postgresql中创建一个表,并在一列上添加注释:

    create table t1 (
       c1 varchar(10)
    );
    comment on column t1.c1 is 'foo';
    

    alter table t1 add column c2 varchar(20);
    

    我想查找第一列的注释内容,并与新列关联:

    select comment_text from (what?) where table_name = 't1' and column_name = 'c1'
    

    (什么?)将是一个系统表,但在pgAdmin中查看并在web上搜索之后,我还没有知道它的名称。

    comment on column t1.c1 is (select ...);
    

    但我有一种感觉,这让事情变得有点牵强。谢谢你的建议。

    更新:根据我在这里收到的建议,我最终编写了一个程序来自动传输注释,作为更改Postgresql列的数据类型的更大过程的一部分。你可以读一下 on my blog

    2 回复  |  直到 17 年前
        1
  •  5
  •   Vinko Vrsalovic    17 年前

    接下来要知道的是如何获取表oid。正如你所怀疑的那样,我认为将此作为评论的一部分是行不通的。

        postgres=# create table comtest1 (id int, val varchar);
        CREATE TABLE
        postgres=# insert into comtest1 values (1,'a');
        INSERT 0 1
        postgres=# select distinct tableoid from comtest1;
         tableoid
        ----------
            32792
        (1 row)
    
        postgres=# comment on column comtest1.id is 'Identifier Number One';
        COMMENT
        postgres=# select col_description(32792,1);
            col_description
        -----------------------
         Identifier Number One
        (1 row)
    

    无论如何,我快速启动了一个plpgsql函数,将注释从一个表/列对复制到另一个表/列对。您必须在数据库上创建Lang plpgsql,并按如下方式使用它:

        Copy the comment on the first column of table comtest1 to the id 
        column of the table comtest2. Yes, it should be improved but 
        that's left as work for the reader.
    
        postgres=# select copy_comment('comtest1',1,'comtest2','id');
         copy_comment
        --------------
                    1
        (1 row)
    
    CREATE OR REPLACE FUNCTION copy_comment(varchar,int,varchar,varchar) RETURNS int AS $PROC$
    DECLARE
            src_tbl ALIAS FOR $1;
            src_col ALIAS FOR $2;
            dst_tbl ALIAS FOR $3;
            dst_col ALIAS FOR $4;
            row RECORD;
            oid INT;
            comment VARCHAR;
    BEGIN
            FOR row IN EXECUTE 'SELECT DISTINCT tableoid FROM ' || quote_ident(src_tbl) LOOP
                    oid := row.tableoid;
            END LOOP;
    
            FOR row IN EXECUTE 'SELECT col_description(' || quote_literal(oid) || ',' || quote_literal(src_col) || ')' LOOP
                    comment := row.col_description;
            END LOOP;
    
            EXECUTE 'COMMENT ON COLUMN ' || quote_ident(dst_tbl) || '.' || quote_ident(dst_col) || ' IS ' || quote_literal(comment);
    
            RETURN 1;
    END;
    $PROC$ LANGUAGE plpgsql;
    
        2
  •  1
  •   kasperjj    17 年前

    this page 详情请参阅。

    推荐文章