【发布时间】:2021-01-16 12:32:33
【问题描述】:
这涵盖了大多数用例How do you use variables in a simple PostgreSQL script?,但不包括 select 子句。
此代码产生错误column "ct" does not exist"
DO
$$
declare CT timestamp := '2020-09-04 23:59:59';
select CT,5 from job;
$$;
我明白为什么它将 CT 解释为列名。在 select 子句的上下文中引用变量所需的 Postgres 语法是什么?
我希望该查询返回
'2020-09-04 23:59:59',5
作业表中的每一行。
已接受答案的附录
我的用例不返回行。相反,选择的结果由插入语句使用。我正在将暂存表中的行转换为其他表,并添加导入日期和拥有插入的身份等值。变量提供的正是这些值——它们被用在几个这样的转换中,变量的重点是让我在脚本顶部设置每个值。
因为这些行是这样消耗的,所以我不需要包装此代码的函数。测试有点不方便,因为我无法运行选择并查看结果而不复制并粘贴文字,但至少可以使用变量。我的工作脚本如下所示:
do
$$
declare ct timestamp := '2020-09-04 23:59:59';
declare cb int := 2;
declare iso8601 varchar(50) := 'YYYY-MM-DD HH24:MI:SS';
declare USAdate varchar(50) := 'MM-DD-YYYY HH24:MI:SS';
begin
delete from dozer_wheel_loader_equipment_movement where created = ct;
INSERT INTO dozer_wheel_loader_equipment_movement
(site, primary_category_id, machine, machine_class, x, y, z, timestamp_local, created, created_by)
select site ,mc.id ,machine , machineclass ,x,y,z,to_timestamp(timestamplocal, iso8601), ct, cb
from stage_dozer_csv d join machine_category mc on d.primarycategory = mc.short_code;
...
end
$$
How to declare a variable in a PostgreSQL query有很多值得一读的相关资料
【问题讨论】:
-
您没有收到
SQL Error [42702]: ERROR: column reference "CT" is ambiguous错误消息吗?我不认为你可以解决这个问题。在变量名称前加上前缀,例如 var_ct,然后select var_ct, 5 from job;会给你想要的结果。顺便说一句,您的 pl/pgsql 块无效。 -
declare启动一个 block 进行声明。它只需要一次。为每个变量创建一个新的declare块效率低且不需要。
标签: postgresql