将字符串转换为列名称

时间:2014-10-09 15:54:06

标签: postgresql plpgsql dynamic-sql

我试图编写一个看起来或多或少的简单postgres函数:

CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users) RETURNS float AS $$
  DECLARE
    sum float;
  BEGIN
    sum = (SELECT SUM($1) FROM jobs WHERE jobs.technician_id = in_t.id);
    RETURN sum;
  END;
$$ LANGUAGE plpgsql;

我需要像这样使用它:

SELECT users.*, USER_TOTALS('jobs.price', users.*) AS total_price_value FROM users;

Hovewer,显然没有工作因为SUM()函数需要获取列名,但是我的代码将varchar传递给它,所以错误说:

Function sum(character varying) does not exist

问题是 - 我可以以某种方式将varchar变量强制转换为列名var类型吗?我现在正在谷歌搜索这个东西大约2个小时,我不知道我怎么能做到这一点。

2 个答案:

答案 0 :(得分:1)

推荐表格:

CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users) 
RETURNS float AS $$
DECLARE 
  sum float;
BEGIN
  EXECUTE format('SELECT SUM(%I) FROM jobs WHERE jobs.technician_id=$1', column_name)
    INTO sum
    USING in_t;
  RETURN sum;
END;
$$ LANGUAGE plpgsql;

答案 1 :(得分:0)

CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users) RETURNS float AS $$
DECLARE 
    sum float;
BEGIN
    EXECUTE 'SELECT SUM('||column_name||') FROM jobs WHERE jobs.technician_id='||in_t INTO sum;
    RETURN sum;
END;
$$ LANGUAGE plpgsql;