gpt4 book ai didi

postgresql - 重命名 postgresql 数据库中的列名

转载 作者:行者123 更新时间:2023-11-29 11:10:33 25 4
gpt4 key购买 nike

我想在 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);

或类似的

关于postgresql - 重命名 postgresql 数据库中的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11898433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com