将列名称传递给函数

时间:2016-11-10 06:49:35

标签: sql postgresql stored-procedures

CREATE OR REPLACE FUNCTION test123(column_name VARCHAR(40)) RETURNS RECORD AS $$
DECLARE   
    rec RECORD ;
BEGIN
    SELECT * INTO rec FROM my_table WHERE column_name=1 LIMIT 1;
    RETURN rec;
END;
$$ LANGUAGE plpgsql;

如何将列名传递给函数,然后在查询中使用该名称?

以上代码不起作用:

error: operator does not exist: character varying = integer

1 个答案:

答案 0 :(得分:3)

如果要在函数内部的查询中使用函数参数作为标识符,则需要动态EXECUTE查询:

CREATE OR REPLACE FUNCTION test123(column_name VARCHAR(40)) RETURNS RECORD AS $$
DECLARE   
    rec RECORD;
BEGIN
    EXECUTE format('SELECT * FROM my_table WHERE %I = 1 LIMIT 1', column_name)
    INTO rec;
    RETURN rec;
END;
$$ LANGUAGE plpgsql;

或更短:

CREATE OR REPLACE FUNCTION test123(column_name VARCHAR(40)) RETURNS RECORD AS $$
BEGIN
    RETURN QUERY EXECUTE format('SELECT * FROM my_table WHERE %I = 1 LIMIT 1', column_name);
END;
$$ LANGUAGE plpgsql;