繁体   English   中英

如何将整数转换为可用作Postgresql中列名称的字符串?

[英]How to convert Integers to Strings that can be used as column names in postgresql?

我正在尝试使用两个循环将INERT插入new_table。 事情是old_table像这样,带有奇怪的“ year-month”列名:

CREATE TABLE old_table
(
    regionname character varying(10),
    "1996-01" integer,
    "1996-02" integer,
    "1996-03" integer,
    ...
    "2014-11" integer,
    "2014-12" integer
)

空的new_table等待数据的格式如下:

CREATE TABLE new_table
(
  regionname character varying(10),
  year integer,
  month integer,
  value integer
)

我想在以下函数中使用参数y和m来创建列名。 例如,当循环中y = 1996且m = 1时,NEEDTOFILL部分应为“ 1996-01”,可以用作列名。

CREATE FUNCTION insertLoop() RETURNS void AS $$
BEGIN
  FOR y IN 1996..2014 LOOP
      FOR m IN 1..12 LOOP
          INSERT INTO new_table(regionname, year, month, value)
          (
              SELECT regionname, y AS year, m AS month, **NEEDTOFILL** AS value
              FROM old_table
              WHERE **NEEDTOFILL** IS NOT NULL
          );
      END LOOP;
  END LOOP;
END; 
$$ LANGUAGE plpgsql;

NEETOFILL应该是什么? 还是有一种方法可以选择第ith列,而不使用SQL中的实际列名? 还是其他方式呢?

您需要使用::将整数转换为varchar并使用||进行连接 喜欢...

y::varchar || '-' || m::varchar 

编辑你是对的。 这将生成值而不是列名。然后,您必须在变量中生成查询,然后执行查询。 像这样的东西

query = 'INSERT INTO new_table(regionname, year, month, value)
          SELECT regionname, y AS year, m AS month, ' || y::varchar || '-' || m::varchar || ' AS value
          FROM old_table
          WHERE ' || y::varchar || '-' || m::varchar || ' IS NOT NULL';
execute query;

暂无
暂无

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

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