在postgresql数据库中重命名列名

前端之家收集整理的这篇文章主要介绍了在postgresql数据库中重命名列名前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将Postgresql数据库中的所有列名重新命名为小写我刚刚编写了一个sql函数.以下是代码.
CREATE OR REPLACE FUNCTION update_column_names() RETURNS boolean AS $$
DECLARE 
aRow RECORD;
aRow2 RECORD;
tbl_name TEXT;
col_name TEXT;
new_col_name TEXT; 
BEGIN
    FOR aRow IN select table_name from information_schema.tables where table_schema='public' and table_type='BASE TABLE' LOOP
        SELECT aRow.table_name INTO tbl_name from current_catalog;
        FOR aRow2 IN select column_name from information_schema.columns where table_schema='public' and table_name = aRow.table_name LOOP
            SELECT aRow2.column_name INTO col_name from current_catalog;
            new_col_name:=lower(col_name);
            RAISE NOTICE 'Table name:%',tbl_name;
            RAISE NOTICE 'Column name:%',aRow2.column_name;
            RAISE NOTICE 'New column name:%',new_col_name;
            ALTER TABLE tbl_name RENAME COLUMN col_name TO new_col_name;
        END LOOP;
    END LOOP;
    RETURN true;
END;
$$LANGUAGE plpgsql;

上面的代码给出关系tbl_name不存在.代码有什么问题?

你需要使用 dynamic SQL这样做;表名不能是变量.
⋮
EXECUTE 'ALTER TABLE ' || quote_ident(tbl_name) || ' RENAME COLUMN '
        || quote_ident(col_name) || ' TO ' || quote_ident(new_col_name);
⋮

或类似

原文链接:https://www.f2er.com/postgresql/192635.html

猜你在找的Postgre SQL相关文章