如何声明变量并在Postgres中的if语句中使用它

问题描述 投票:0回答:1

我想根据查询结果创建一个变量,然后在IF语句中使用它。到目前为止,我有这个:

with variable as (select "Id" from public.tableName where "Id" = 24)

if variable notnull then
    insert into public.tableName ("OtherName", "OtherPhoneNumber", "OtherAddress", "Id")
    overriding system values
    values ('foo', '205-123-4567', '123 Sample Ln', variable)
end if

Postgres给我一个错误,显示为:

SQL错误[42601]:错误:“如果”或附近的语法错误

我在做什么错?

postgresql
1个回答
0
投票

您可以如下使用insert ... select语法:

insert into public.tableName ("OtherName", "OtherPhoneNumber", "OtherAddress", "Id")
select 'foo', '205-123-4567', '123 Sample Ln', "Id"
from public.tableName 
where "Id" = 24
© www.soinside.com 2019 - 2024. All rights reserved.