首页 > 解决方案 > 如果函数的参数与列名相同怎么办

问题描述

我有一个 SQL 函数,其参数名称为 id。但是,我有一个具有相同名称的列名 id。我如何告诉函数如何区分参数和列。如果我将参数名称从 id 更改为 num,我的函数将完美运行,但这不是这里的选项,我也无法更改列名。

create or replace function
    test(id integer) return text
as $$
    select address
    from customers c
    where c.id = id
$$ language sql;

标签: sqldatabasepostgresqlsql-function

解决方案


Postgres 允许您按位置引用参数:

create or replace function
    test(id integer) return text
as $$
    select address
    from customers c
    where c.id = $1
$$ language sql;

我认为这是一种不好的做法,一个班级不应该鼓励这种风格。实际上,应该鼓励您为不太可能与其他标识符冲突的参数命名:

create or replace function test (
        in_id integer
) return text
as $$
    select address
    from customers c
    where c.id = in_id
$$ language sql;

推荐阅读