简体   繁体   English

将所有列名称更改为小写 Postgresql

[英]Change all column names to lowercase Postgresql

I am having an issue with my postgresql database.我的 postgresql 数据库有问题。 I added 5 Tables with a lot of data and a lot of columns.我添加了 5 个包含大量数据和大量列的表。 Now I noticed I added the columns with a mix of upper and lowercase letters, which makes it difficult to query them using sqlalchemy or pandas.read_sql_query, because I need double quotes to access them.现在我注意到我添加了混合大小写字母的列,这使得使用 sqlalchemy 或 pandas.read_sql_query 查询它们变得困难,因为我需要双引号来访问它们。 Is there a way to change all values in the column names to lowercase letters with a single command?有没有办法用一个命令将列名中的所有值更改为小写字母?

Im new to SQL, any help is appreciated.我是 SQL 的新手,感谢您的帮助。

Use an anonymous code block with a FOR LOOP over the table columns:在表列上使用带有FOR LOOPanonymous code block

DO $$
DECLARE row record;
BEGIN
  FOR row IN SELECT table_schema,table_name,column_name
             FROM information_schema.columns
             WHERE table_schema = 'public' AND 
             table_name   = 'table1'
  LOOP
    EXECUTE format('ALTER TABLE %I.%I RENAME COLUMN %I TO %I',
      row.table_schema,row.table_name,row.column_name,lower(row.column_name));  
  END LOOP;
END $$;

Demo: db<>fiddle演示: db<>fiddle

If you wish to simply ensure that the query returns lowercase (without changing the original entries), you can simply input:如果您希望简单地确保查询返回小写字母(而不更改原始条目),您只需输入:

select lower(variable) from table;

On the other hand, if you wish to actually change the case in the table itself, you must use an UPDATE command.另一方面,如果您希望实际更改表本身的大小写,则必须使用 UPDATE 命令。

UPDATE table SET variable = LOWER(variable);

Something like that should do the trick:像这样的东西应该可以解决问题:

 SELECT LOWER(column) FROM my_table;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM