2016-11-10 90 views
0
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

您需要動態SQL的。有關示例,請參閱手冊:https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN –

回答

2

當你想在一個函數內部查詢中使用函數參數標識符你需要動態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;