如何在Postgres sql函数中引用命名参数? [英] How do I reference named parameters in Postgres sql functions?

查看:109
本文介绍了如何在Postgres sql函数中引用命名参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处是Postgres noobie。

Postgres noobie here.

我正在尝试将SQL Server存储的proc转换为Postgres函数。当前无法弄清楚如何将此SQL行转换为Postgres。

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.

SQL Server:

SQL Server:

input: @name = null

SELECT *
FROM table
WHERE name = ISNULL(@name, name)

Postgres:

input: n = null

SELECT *
FROM table
WHERE name = COALESCE(n, name)

我收到错误消息第n列不存在。如何在Postgres函数的select语句中引用参数?

I'm getting the error "column n does not exist." How do I reference parameters in select statements in Postgres functions?

UPDATE:

Postgres函数的定义

Definition of Postgres function

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(n, u.name);

$$
LANGUAGE sql;


推荐答案

已修改:如评论中指出,此答案在2012年初编写时是准确的,但自2012年末发布的v9.2起,已支持命名参数。

您的函数位于语言SQL 中。您可以在定义为 language plpgsql 的存储过程中按名称使用参数。

Parameter names are merely decoration when your function is in language SQL. You can use the parameters by name in stored procedures defined as language plpgsql.

因此,必须引用使用$ X的函数args,其中X是函数参数列表的顺序位置(从1开始)。

Consequently, you must refer to the function args using $X where X is the ordinal position of the function's argument list (starting with 1).

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

这篇关于如何在Postgres sql函数中引用命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆