How do I reference named parameters in Postgres sql functions?

前端 未结 2 710
野趣味
野趣味 2021-01-17 12:28

Postgres noobie here.

I\'m trying to convert a SQL Server stored proc into a Postgres function. Currently cannot figure out how to turn this SQL line into Postgres.

2条回答
  •  旧巷少年郎
    2021-01-17 13:16

    You cannot use named parameters in a function that is defined with language=SQL.

    You need to use the the placeholder $1.

    CREATE OR REPLACE FUNCTION fn_name (n VARCHAR(32) = NULL, name OUT varchar(32), description OUT varchar(64))
    RETURNS setof record
    AS 
    $$
        SELECT u.name
            , u.description
        FROM table_a u
        WHERE u.name = COALESCE($1, u.name);
    
    $$
    LANGUAGE sql;
    

    This behaviour is documented in the manual: http://www.postgresql.org/docs/9.0/static/xfunc-sql.html

    So far as the SQL function itself is concerned, these names are just decoration; you must still refer to the parameters as $1, $2, etc within the function body

    Edit

    Since version 9.2 it is possible to use named parameters with (plain) SQL function
    http://www.postgresql.org/docs/9.2/static/xfunc-sql.html#XFUNC-SQL-FUNCTION-ARGUMENTS

提交回复
热议问题